Sub topic 4
Weighted graphs: edges that carry a value
This chapter assumes you can use Python dictionaries and loops, and that you know the undirected and directed graphs from the earlier chapters. Here you add a number to each edge, store it, and use it to compare paths.
What a weight is
A weighted graph is a graph in which each edge has a value called its weight. The weight measures something about the connection, such as distance, travel time, cost, or capacity. The graph can be directed or undirected. Weight is a separate property from direction.
A plain graph answers "is there a connection?". A weighted graph also answers "how much does the connection cost?". That second question makes it possible to ask for the cheapest route instead of just any route.
Storing weights in an adjacency list
In the dictionary-of-dictionaries form, the inner dictionary maps each neighbor to the edge weight. An unweighted graph is the special case where every weight is 1.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(weighted)
# {'A': {'B': 4, 'C': 1}, 'B': {'A': 4, 'C': 2}, 'C': {'A': 1, 'B': 2}}
print(weighted["A"]["B"]) # 4Because the graph is undirected, add_edge stores each weight twice, once in each direction. If you update one copy and forget the other, the graph becomes inconsistent. Always change weights through add_edge.
Path weight
The weight of a path is the sum of the weights of its edges. The number of edges no longer decides which path is shorter.
def path_weight(graph, path):
return sum(graph[u][v] for u, v in zip(path, path[1:]))
print(path_weight(weighted, ["A", "B"])) # 4
print(path_weight(weighted, ["A", "C", "B"])) # 3The direct edge from A to B uses one edge and costs 4. The route through C uses two edges and costs 3. A breadth-first search would pick the direct edge, because it counts edges. To minimize total weight you need a different algorithm, which a later chapter covers.
Common errors
- Treating a missing edge as weight 0. No edge means no connection. In an adjacency list this is correct by default, because the neighbor is absent. In an adjacency matrix you need a separate marker, such as
Noneorfloat("inf"). - Assuming every weight is a cost. A weight can also be a capacity or a similarity score, where larger is better. Decide whether you want the smallest or the largest total before you choose an algorithm.
- Ignoring negative weights. They are legal in a weighted graph. Some algorithms, including Dijkstra's, give wrong answers when any weight is negative.
- Mixing units. Distances in kilometers and miles on the same graph give meaningless totals.
Choosing a model
| Question | Model |
|---|---|
| Is A connected to B? | Unweighted graph |
| Does the link go only one way? | Directed graph |
| Does each link have a cost or size? | Weighted graph |
| One-way links that also have a cost? | Directed and weighted graph |
Exercise
Using the weighted graph above, what does path_weight(weighted, ["B", "C", "A"]) return, and why does it differ from path_weight(weighted, ["B", "A"])?
Show answer
It returns 3, because edge B-C has weight 2 and edge C-A has weight 1. The direct path B-A returns 4. The path through C has more edges but a smaller total weight.
Exercise
A road graph stores a travel time of 0 minutes for a pedestrian shortcut between two points. Why is if graph[u][v]: a bad way to check that the shortcut exists, and what should you write instead?
Show answer
The weight 0 is falsy in Python, so the check treats the shortcut as missing. Write if v in graph[u]:.