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.

In plain Python you can store a directed weighted graph as a dict of dicts: graph[u][v] = weight means an edge from u to v. Building that structure from an edge list is enough for many course exercises; specialised libraries exist, but the idea does not depend on them.

graph = {}
for u, v, w in edges:
    graph.setdefault(u, {})[v] = w

Shortest path on non-negative weights is Dijkstra: keep the best known distance to each node, and always expand the closest unsettled node next. Centrality and connected components are the same idea at larger scale: walk the adjacency data instead of joining tables.

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 (as a data structure) 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. Print the length (sum of weights) of the shortest path from src to dst. Weights are non-negative. Assume a path exists. Round to 1 decimal. Use only the standard library (no NetworkX).

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.
Question 3

Why is Dijkstra safe for this shortest-path task?

Card Info
  • Topic: Python for Data Science
  • Difficulty: Advanced
  • Completed: 0 users
Creator
Best
Best
BestBuddy