Real routing systems (maps, network overlays) start with a graph: nodes are locations or routers, and each directed edge carries a weight such as distance or latency.
Implement add_edge(u, v, w) so it records a directed edge from u to v with weight w inside the adjacency dict self.adj. Store each node's outgoing edges as a list of (neighbor, weight) tuples under self.adj[u], creating the list the first time a node appears.
The helper neighbors(u) is already written for you: it returns the list of outgoing edges for u, or an empty list when u is unknown.
Edges are directed: add_edge("A", "B", 4) does not create an edge from B to A.
import heapq
class WeightedGraph:
def __init__(self):
self.adj = {}
def add_edge(self, u, v, w):
"""Add a directed edge u -> v with weight w to the adjacency dict."""
# TODO: append (v, w) to the list at self.adj[u], creating it if missing
pass
def neighbors(self, u):
return self.adj.get(u, [])
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Real routing systems (maps, network overlays) start with a graph: nodes are locations or routers, and each directed edge carries a weight such as distance or latency.
Implement add_edge(u, v, w) so it records a directed edge from u to v with weight w inside the adjacency dict self.adj. Store each node's outgoing edges as a list of (neighbor, weight) tuples under self.adj[u], creating the list the first time a node appears.
The helper neighbors(u) is already written for you: it returns the list of outgoing edges for u, or an empty list when u is unknown.
Edges are directed: add_edge("A", "B", 4) does not create an edge from B to A.
Press Run Tests or ββ© to check your solution.