Graphs: relationships as data and algorithms

Advanced Python for Data Science
Created by Best · 24.06.2026 at 14:03 UTC

A graph is relationships as data: nodes connected by edges. Social networks, task dependencies, citations, money moving between accounts, products bought together — all are naturally graphs, and questions like "what's the shortest path?" or "who is most connected?" are awkward on a table but native to a graph.

import networkx as nx
G = nx.DiGraph()                              # a directed graph
G.add_weighted_edges_from([("a", "b", 1.0),
                           ("b", "c", 2.0)])

You build a graph by adding edges (optionally weighted); recognising when a problem is graph-shaped is itself a valuable skill.

Once a graph is built, you call ready-made algorithms:

nx.shortest_path_length(G, "a", "c", weight="weight")   # cheapest route
nx.degree_centrality(G)                                 # how connected each node is
list(nx.connected_components(G.to_undirected()))        # the separate clusters

Shortest path finds the cheapest route between two nodes; centrality measures influence by connectedness; connected components find the separate islands in the network. The graph view often turns a hard table query into a one-line call.
dataclasses” and leads into “Reproducibility: environments, containers, seeds”.*

University approvals: 0
Related cards
Builds on __slots__, the walrus, and when to use dataclasses · Python for Data Science
Next Reproducibility: environments, containers, seeds · Python for Data Science
Tasks
Question 1

What does a graph (in the NetworkX sense) model?

Question 2

stdin: line 1 = integer E (edge count); next E lines each u v w (directed edge u->v with float weight w); last line = src dst. Using NetworkX, print the length (sum of weights) of the shortest path from src to dst. Assume a path exists. Round to 1 decimal.

Example input:

3
a b 1
b c 2
a c 5
a c

Expected output:

3.0
3 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Python for Data Science
  • Difficulty: Advanced
  • Completed: 0 users
Creator
Best
Best
BestBuddy