Sub topic 2
Undirected graphs: symmetric relationships
This chapter assumes you can write Python with dictionaries, sets, and functions, and that you know basic big-O notation. It covers one graph type: the undirected graph.
The working model
An undirected graph is a set of vertices and a set of edges, where each edge joins two vertices and has no direction. An edge between A and B means A is connected to B and B is connected to A. The relationship is symmetric.
Good fits for this model include:
- Friendships on a network where both people must agree.
- Roads that allow travel in both directions.
- Network cables between two machines.
If the real relationship is one-way, such as "follows" or "links to", an undirected graph loses information. The next chapter covers directed graphs for that case.
Formally, an edge is an unordered pair, written {A, B}. The pairs {A, B} and {B, A} are the same edge.
Storing symmetry
An adjacency list keeps, for each vertex, the neighbors it connects to. For an undirected graph, you must record each edge twice: once under each endpoint. This code stores the graph as a dictionary of dictionaries, which also leaves room for weights later.
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
undirected = {}
add_edge(undirected, "A", "B")
add_edge(undirected, "B", "C")
print(undirected) # {'A': {'B': 1}, 'B': {'A': 1, 'C': 1}, 'C': {'B': 1}}The line graph[v][u] = weight runs only when directed is false. It is what makes the graph undirected. The line graph.setdefault(v, {}) makes sure a vertex with no outgoing entries still appears as a key. Without it, a later lookup such as graph["C"] would raise a KeyError.
Checking the symmetry invariant
A correct undirected graph always satisfies this rule: if v is in graph[u], then u is in graph[v]. You can test it directly.
def is_symmetric(graph):
return all(u in graph[v] for u in graph for v in graph[u])
print(is_symmetric(undirected)) # TrueThis check is useful when you build graphs by hand or load them from data. A graph that breaks the rule is effectively directed, and algorithms that assume symmetry will give wrong answers on it.
Common errors
- Storing only one direction. If you write
graph["A"]["B"]but notgraph["B"]["A"], then a search starting from B never reaches A. Use one helper such asadd_edgefor every insertion so both sides stay in sync. - Forgetting isolated vertices. A vertex with no edges is still part of the graph. Add it with
graph.setdefault(v, {}). - Counting edges twice. Each edge appears in two adjacency entries. The total number of entries is twice the number of edges, so divide by two when you count edges.
- Self-loops. An edge from a vertex to itself, such as {A, A}, is allowed in some definitions. The code above stores it once, because
graph[u][u]andgraph[v][u]are the same slot. Decide up front whether your problem permits loops.
Counting edges
Because every edge is stored twice, the edge count is half the sum of all neighbor-set sizes.
def edge_count(graph):
return sum(len(neighbors) for neighbors in graph.values()) // 2
print(edge_count(undirected)) # 2This calculation is wrong if the graph has self-loops, since each loop is stored once. The sum would then be odd for some graphs.
Exercise
You build an undirected graph with addedge(g, "X", "Y") and addedge(g, "Y", "Z"), then manually delete the entry g["Z"]["Y"] to remove an edge. Does is_symmetric(g) still return True? Which edge is now only half-removed?
Show answer
No. is_symmetric(g) returns False. The edge between Y and Z is half-removed: g["Y"]["Z"] still exists, but g["Z"]["Y"] is gone. A correct removal deletes both entries, so the graph stays symmetric.