Sub topic 5
Degree, in-degree, and out-degree
This chapter assumes you can read Python dictionaries and sets and know the adjacency-list form built earlier: a dictionary that maps each vertex to a dictionary of its neighbors and edge weights.
Degree in an undirected graph
The degree of a vertex is the number of edges attached to it. In an undirected graph, an edge has no direction, so each edge counts once for each of its two endpoints.
With the adjacency list, the degree of u is the number of neighbors stored under u. That is len(graph[u]). The lookup is O(1).
Summing the degrees of all vertices counts every edge twice, once from each end. This gives the handshake rule:
sum of degrees = 2 × (number of edges)
If the sum you compute is odd, the graph data is broken. This makes the rule a cheap sanity check.
In-degree and out-degree in a directed graph
A directed edge goes from a source to a target, so the two ends play different roles. Directed graphs therefore split degree in two:
- The out-degree of
uis the number of edges leavingu. - The in-degree of
uis the number of edges arriving atu.
In this graph, A and C each have out-degree 1 and in-degree 0. Vertex B has in-degree 2 and out-degree 0.
Computing both in code
The adjacency list stores outgoing edges only. Out-degree is therefore a direct lookup. In-degree has to search for every vertex that lists u as a neighbor.
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
def out_degree(graph, u):
return len(graph[u])
def in_degree(graph, u):
return sum(1 for v in graph if u in graph[v])
g = {}
add_edge(g, "A", "B", directed=True)
add_edge(g, "C", "B", directed=True)
print(out_degree(g, "A")) # 1
print(in_degree(g, "B")) # 2out_degree takes O(1) time. in_degree checks every vertex, so it takes O(V) time. If you need in-degrees often, compute them all in one pass over the edges and keep the result:
def all_in_degrees(graph):
counts = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
counts[v] += 1
return counts
print(all_in_degrees(g)) # {'A': 0, 'B': 2, 'C': 0}This pass takes O(V + E) time for the whole graph. Doing it once is cheaper than calling in_degree for every vertex, which costs O(V²) in total.
For directed graphs, there is a second counting rule. Each edge leaves exactly one vertex and enters exactly one vertex. So the sum of all in-degrees equals the sum of all out-degrees, and both equal the number of edges.
Common errors
- Using
len(graph[u])as the in-degree. That value is the out-degree. The two match only by coincidence. - Counting weights instead of edges. Degree counts edges, not their weights. In a weighted graph, the sum of the weights at a vertex is a different quantity, often called the weighted degree or strength. It is
sum(graph[u].values()). - Forgetting self-loops. A self-loop is an edge from a vertex to itself. By the usual convention, it adds 2 to an undirected degree. The dictionary form stores it as one entry, so
len(graph[u])counts it once. If your data can contain self-loops, add 1 for eachuingraph[u]to follow the convention. - Assuming a missing key means degree 0.
add_edgecreates an empty entry for every target vertex, sograph[u]always exists. If you build the dictionary by hand, make sure every vertex has a key. Otherwisegraph[u]raisesKeyError.
Exercise
A directed graph has the edges A->B, A->C, C->B, and B->D. Give the in-degree and out-degree of each vertex. Then check that the sum of the in-degrees equals the sum of the out-degrees.
Show answer
A has in-degree 0 and out-degree 2. B has in-degree 2 (from A and C) and out-degree 1 (to D). C has in-degree 1 and out-degree 1. D has in-degree 1 and out-degree 0. The in-degrees sum to 0 + 2 + 1 + 1 = 4, and the out-degrees sum to 2 + 1 + 1 + 0 = 4. Both equal the number of edges, 4.