Sub topic 1
What a Graph Is: Vertices and Edges
Prerequisites
This chapter assumes you can do the following:
- Write basic Python with lists, dictionaries, sets, and functions.
- Read simple big-O notation such as O(1) and O(n).
- Use queues and stacks.
You don't need any graph theory. This chapter introduces the vocabulary that the rest of the tutorial builds on.
The working model
A graph is a pair of collections: a set of vertices (also called nodes) and a set of edges. Each edge connects two vertices. Vertices stand for things, and edges stand for relationships between those things.
Many problems fit this shape:
- Cities are vertices, and roads between them are edges.
- People are vertices, and friendships are edges.
- Tasks are vertices, and "must finish before" links are edges.
Formally, a graph is written G = (V, E). V is the vertex set and E is the edge set. Each edge is a pair of vertices, such as (A, B). Two vertices joined by an edge are adjacent, or neighbors.
A graph carries no layout. Where you draw the vertices on the page does not change the graph. Only the vertices and the edges matter.
A small example
Take three vertices, A, B, and C, and two edges, A–B and B–C. Here V = {A, B, C} and E = {(A, B), (B, C)}.
A is not adjacent to C, because no edge joins them. You can still get from A to C by going through B. Chapter 6 formalizes that idea as a path.
Three questions that define the graph type
The tutorial covers three kinds of graph. Each one answers a different question about an edge.
| Question about an edge | If the answer is yes | Graph type |
|---|---|---|
| Does it have a direction? | Edge (A, B) is not the same as (B, A) | Directed |
| Does it work both ways? | Edge (A, B) is the same as (B, A) | Undirected |
| Does it carry a value? | Each edge has a number, such as a cost or distance | Weighted |
The first two are opposites. Weight is a separate choice, so a graph can be directed and weighted, or undirected and weighted. The next three chapters cover each type.
Representing a graph in code
The simplest way to store a graph in Python is a dictionary. Each key is a vertex. Each value is the set of that vertex's neighbors.
graph = {
"A": {"B"},
"B": {"A", "C"},
"C": {"B"},
}
def neighbors(graph, vertex):
return graph[vertex]
def has_edge(graph, u, v):
return v in graph[u]
print(sorted(neighbors(graph, "B"))) # ['A', 'C']
print(has_edge(graph, "A", "B")) # True
print(has_edge(graph, "A", "C")) # False
vertex_count = len(graph)
edge_count = sum(len(n) for n in graph.values()) // 2
print(vertex_count, edge_count) # 3 2This graph is undirected, so every edge appears twice: B is in A's set, and A is in B's set. That is why the edge count divides the total by 2. A later chapter explains this representation, called an adjacency list, in full.
Common errors
- Confusing a vertex with its data. A vertex is an identity, such as "A" or a city name. Facts about it, such as population, belong in a separate dictionary keyed by vertex.
- Forgetting the reverse entry. If you model an undirected graph and add only
graph["A"].add("B"), you have built a directed edge by accident. - Treating the drawing as the graph. Two diagrams with different layouts can describe the same graph.
- Mixing up counts. The number of vertices is |V|, and the number of edges is |E|. Later cost analysis uses both.
Exercise
A graph has V = {1, 2, 3, 4} and E = {(1, 2), (2, 3)}. Is vertex 4 part of the graph? Which vertices are adjacent to 2? Write the dictionary-of-sets form.
Show answer
Yes, vertex 4 is part of the graph. It is an isolated vertex with no edges, because V lists it. Vertices 1 and 3 are adjacent to 2. Treating the edges as undirected, the dictionary is {1: {2}, 2: {1, 3}, 3: {2}, 4: set()}.
Exercise
In the code above, what would has_edge(graph, "C", "A") return, and why?
Show answer
It returns False. The set for "C" is {"B"}, which does not contain "A", so no edge joins C and A.