本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
9Graphs: Networks of Roads and People
A rumour starts in Brenmoor: the library will open on Sundays. Each person who hears it tells their friends the next day. If it starts with the right person, how many days until everyone who can hear it has heard it? And who is the right person?
The question is not about anyone’s personality: it is about the shape of the network of friendships. The same shape appears in the roads between places, the links between web pages and the cables between computers. This chapter names that shape, a graph, stores it in Python, measures distances in it, and finds its centre.
You already know
A dictionary maps keys to values, and a set holds values without order or repetition (Book 1, grade 8, and the chapter on tuples and sets). The Earth and space sciences book explains how a satellite receiver works out its own position on the Earth (grade 9); a map then turns that position into a route.
9.1 Vertices and edges
Definition 9.1 (Graph, vertex, edge)
A graph is a set of vertices together with a set of edges, each edge joining two different vertices. Two vertices joined by an edge are adjacent.
In the friendship graph of Brenmoor the vertices are the people to , and an edge joins two friends. In the road graph the vertices are the places, and an edge is a road.
Definition 9.2 (Degree, neighbour)
The neighbours of a vertex are the vertices adjacent to it. Its degree is the number of its neighbours.
Definition 9.3 (Directed graph, weighted graph)
In a directed graph each edge goes from one vertex to another, like a one-way street: an edge from to does not let you go from to . A vertex then has an out-degree, the number of edges leaving it, and an in-degree, the number of edges arriving. In a weighted graph each edge carries a number, its weight: a length in metres, a time, a price.
9.2 A graph in Python
A graph is stored as a dictionary from each vertex to the set of its neighbours. An undirected edge is written at both of its ends; a vertex without any edge still gets an empty set, so that it is not forgotten.
import csv
def load_friends(path, people=range(1, 41)):
"""Return the friendship graph: a dict person -> set of friends."""
g = {p: set() for p in people} # every person is a vertex, even without friends
with open(path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
a, b = int(row["person_a"]), int(row["person_b"])
g[a].add(b) # an undirected edge is stored
g[b].add(a) # at both of its ends
return g
if __name__ == "__main__":
g = load_friends("friendships.csv")
print(len(g), "vertices")
print("friends of 1:", sorted(g[1]), " friends of 28:", sorted(g[28]))
print("without friends:", [p for p in g if not g[p]])
$ python load_friends.py
40 vertices
friends of 1: [5, 7, 10, 12, 28] friends of 28: [1, 34, 36, 37, 39]
without friends: [40]
from load_friends import load_friends
g = load_friends("friendships.csv")
degree = {p: len(g[p]) for p in g}
count = {}
for d in degree.values():
count[d] = count.get(d, 0) + 1
for d in sorted(count):
print(f"degree {d}: {count[d]:2} people " + "#" * count[d])
print("sum of degrees:", sum(degree.values()))
print("most friends:", [p for p in g if degree[p] == max(degree.values())])
$ python degree_table.py
degree 0: 1 people #
degree 1: 10 people ##########
degree 2: 10 people ##########
degree 3: 10 people ##########
degree 4: 5 people #####
degree 5: 4 people ####
sum of degrees: 100
most friends: [1, 12, 23, 28]
Proposition 9.4 (Sum of the degrees)
In an undirected graph, the sum of the degrees of the vertices is twice the number of edges.
The proof is Exercise 9.12. A road graph needs weights, and one-way roads make it directed: the listing stores a dictionary of neighbours with their distances, and writes a two-way road as two directed edges.
import csv
def load_roads(path):
"""Return the road graph: a dict place -> dict neighbour -> length in metres."""
g = {}
with open(path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
a, b = int(row["from_place"]), int(row["to_place"])
g.setdefault(a, {})[b] = int(row["length_m"])
g.setdefault(b, {})
if row["one_way"] == "0": # a two-way road is two directed edges
g[b][a] = int(row["length_m"])
return g
if __name__ == "__main__":
g = load_roads("roads.csv")
print(len(g), "places,", sum(len(n) for n in g.values()), "directed edges")
print("from 1 (Town Square):", g[1])
print("from 3 (Library): ", g[3])
$ python load_roads.py
30 places, 105 directed edges
from 1 (Town Square): {3: 1360, 23: 1210, 24: 1590, 26: 1560}
from 3 (Library): {24: 1040, 26: 1790}
A program that builds a graph by hand can forget one end of an edge. The check is short: every edge must have its reverse, except the one-way roads.
from load_friends import load_friends
from load_roads import load_roads
def one_way_edges(g):
"""Return the edges (a, b) of g whose reverse (b, a) is missing."""
return [(a, b) for a in g for b in g[a] if a not in g[b]]
print("friendships:", one_way_edges(load_friends("friendships.csv")))
print("roads: ", one_way_edges(load_roads("roads.csv")))
$ python check_symmetric.py
friendships: []
roads: [(1, 3)]
9.3 Paths and distance
Definition 9.5 (Path, length of a path)
A path is a sequence of vertices in which each one is adjacent to the next (in a directed graph, joined by an edge going from it to the next). Its length is its number of edges, or, in a weighted graph, the sum of the weights of its edges.
Definition 9.6 (Distance)
The distance from a vertex to a vertex is the length of a shortest path from to . If there is no such path, there is no distance.
Definition 9.7 (Connected graph, component)
An undirected graph is connected if there is a path between any two of its vertices. A connected component is a largest set of vertices joined to one another by paths.
Computing distances in a large graph is an algorithm of its own, written in grade 12. Here two functions are given, in the file given_graphs.py of the grade’s folder, and used without reading them: distances(g, a) returns the dictionary of the distances, in edges, from a to every vertex it can reach, and components(g) returns the components, largest first.
from given_graphs import components
from load_friends import load_friends
g = load_friends("friendships.csv")
for part in components(g):
people = [str(p) for p in sorted(part)]
shown = people if len(people) <= 12 else people[:12] + ["..."]
print(len(part), "people:", ", ".join(shown))
$ python components.py
29 people: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...
10 people: 15, 16, 17, 19, 21, 22, 23, 24, 26, 27
1 people: 40
On a small weighted map, a shortest route can be found by hand with a frontier: keep the distance from the start of every place reached so far, and repeatedly settle the unsettled place with the smallest one, then look at the roads leaving it.
9.4 Radius, diameter and centre
Definition 9.8 (Eccentricity, radius, diameter, centre)
In a connected graph, the eccentricity of a vertex is its largest distance to another vertex. The radius of the graph is the smallest eccentricity, its diameter the largest one, and its centre the set of the vertices whose eccentricity is the radius.
The rumour of the opening question is a question about eccentricity: started by a person of eccentricity , it reaches everyone in that person’s component after days. On the largest component of the friendship graph:
from given_graphs import components, distances
from load_friends import load_friends
g = load_friends("friendships.csv")
from_1 = distances(g, 1)
for d in range(max(from_1.values()) + 1):
print(f"at distance {d} from 1:", sorted(v for v in from_1 if from_1[v] == d))
largest = components(g)[0]
eccentricity = {v: max(distances(g, v).values()) for v in largest}
radius = min(eccentricity.values())
diameter = max(eccentricity.values())
print("radius", radius, " diameter", diameter)
print("centre:", [v for v in sorted(largest) if eccentricity[v] == radius])
print("eccentricity 7:", [v for v in sorted(largest) if eccentricity[v] == diameter])
$ python distances_given.py
at distance 0 from 1: [1]
at distance 1 from 1: [5, 7, 10, 12, 28]
at distance 2 from 1: [2, 6, 8, 9, 11, 20, 34, 36, 37, 39]
at distance 3 from 1: [3, 4, 13, 14, 18, 25, 29, 30, 32, 33]
at distance 4 from 1: [31, 35, 38]
radius 4 diameter 7
centre: [1, 28]
eccentricity 7: [3, 4, 13, 14, 18, 31, 35, 38]
Remark 9.9
people, each with at most friends, and yet everyone is within steps of everyone in the component. In large networks of people the distances are surprisingly small, a property called the small world: even with a few friends each, the number of people within steps multiplies at each step, so it grows very fast with .
Method 9.10 (Finding the centre of a small graph by hand)
- For each vertex, write the distance to every other vertex, by layers: its neighbours at , their new neighbours at , and so on.
- Its eccentricity is the number of the last layer.
- The radius is the smallest eccentricity, the diameter the largest; the centre is the vertices of eccentricity equal to the radius.
A map application turns a satellite position into a vertex of the road graph, and a route into a shortest path. The receiver gives its position as text, in a standard sentence format: Exercise 9.11 decodes one.
9.5 Exercises
Exercise 9.1 ★
A graph has vertices with degrees , , , and . How many edges does it have? Can a graph have degrees , , ?
Exercise 9.2 ★
Write the dictionary of sets of the undirected graph of the first drawing of the chapter (vertices A, B, C, D).
Solution
Solution of Exercise 9.2.
{"A": {"B", "C"}, "B": {"A", "C", "D"}, "C": {"A", "B"}, "D": {"B"}}: each of the four edges appears twice.
Exercise 9.3 ★
In the graph of eccentricities, give the distance from A to G and from E to F. Give two different shortest paths from B to D, or explain why there is only one.
Exercise 9.4 ★
A graph has the edges –, –, – and the vertices to . List its components. How many edges would make it connected, at least?
Exercise 9.5 ★
Write degree(g, v), and use it to print the people of the friendship graph whose degree is .
Exercise 9.6 ★★
A function add_friendship(g, a, b) only writes g[a].add(b). After building the graph with it, which listing of the chapter detects the problem, and what does it print? Correct the function.
Solution
Solution of Exercise 9.6.
Each friendship is stored only at its first person, so the check of symmetry prints all friendships as edges without a reverse, instead of an empty list. The correct function also writes g[b].add(a) (exercises/graph_tools.py).
Exercise 9.7 ★★
Write is_path(g, seq), which says whether a list of vertices is a path of g. Check that [3, 2, 10, 1, 28] is a path of the friendship graph and [3, 1] is not.
Solution
Solution of Exercise 9.7.
Return False for an empty list or a first vertex outside the graph; otherwise check that every vertex but the last has the next one among its neighbours: all(seq[i + 1] in g[seq[i]] for i in range(len(seq) - 1)) (exercises/graph_tools.py). –, –, – and – are friendships; – is not.
Exercise 9.8 ★★
Draw the graph with edges –, –, –, –, –. Give the eccentricity of each vertex, the radius, the diameter and the centre.
Exercise 9.9 ★★
In the directed drawing of the chapter, give the in-degree and out-degree of every vertex. Check that the in-degrees and the out-degrees have the same sum, and say why that is always so.
Exercise 9.10 ★★
Write edges_from_dict(g), which returns the set of the edges of an undirected graph, each written once as a pair (smaller, larger). Check the sum of the degrees on the friendship graph.
Exercise 9.11 ★★
A satellite receiver sends lines of text such as
$GPGGA,093015.00,4807.0381,N,00131.5240,W,1,08,0.9,62.4,M,47.2,M,,*41
The fields after GPGGA are the time (hours, minutes, seconds), the latitude as degrees and minutes (ddmm.mmmm), N or S, the longitude as dddmm.mmmm, E or W, then the quality of the fix, the number of satellites, a precision figure and the altitude in metres. Give the time, and the latitude and longitude in decimal degrees, west and south counted negative. The two digits after * are a check: the exclusive or of the codes of all characters between $ and *, in hexadecimal. What is it for?
Solution
Solution of Exercise 9.11.
The time is 09:30:15 (on the satellites’ universal time). Latitude: degrees north. Longitude: degrees west, so (exercises/nmea.py). The check lets the receiving program detect a line damaged on the way: if one character changed, the exclusive or almost surely differs from 41, and the line is thrown away.
Exercise 9.12 ★★★
Prove that in an undirected graph the sum of the degrees is twice the number of edges. Deduce that the number of vertices of odd degree is even.
Solution
Solution of Exercise 9.12.
Count the pairs (vertex, edge) where the edge touches the vertex. Counted by vertex, each vertex is in pairs, which gives the sum of the degrees. Counted by edge, each edge touches exactly two vertices, which gives . So the sum of the degrees is , an even number; the vertices of even degree add an even amount, so the odd degrees must add up to an even number too, and there is an even number of them.
Exercise 9.13 ★★★
Prove that in a connected graph, . For the second inequality, take a vertex of the centre and two vertices and , and go from to through .
Solution
Solution of Exercise 9.13.
The radius is the smallest eccentricity and the diameter the largest, so . Take in the centre and any two vertices and . A path from to followed by a path from to is a path from to (it may be shortened if it repeats a vertex), so . This holds for every pair, so the diameter is at most . The graph of eccentricities reaches it: radius , diameter .
Exercise 9.14 ★★★
Write common_friends(g, a, b) with a set intersection, then triangles(g), the number of groups of three people who are all friends with one another. Why does adding the common friends of the two ends of every edge count each triangle three times? How many triangles has the friendship graph?
Exercise 9.15 ★★★
A tiny web has five pages, P1 to P5, and links P1P2, P1P3, P2P3, P4P3, P5P4, P3P1. Rank the pages by in-degree. Then give each page one vote, which it shares equally among the pages it links to, and add the votes each page receives. Which page is first in each ranking? Explain why a search engine would rather count a link from an important page as worth more.
Solution
Solution of Exercise 9.15.
In-degrees: P3 has , P1, P2 and P4 have , P5 has . Votes: P1 gives to P2 and to P3; P2, P4 and P3 give their whole vote to P3, P3 and P1; P5 gives its vote to P4. Totals: P3 , P1 , P4 , P2 , P5 . P3 is first both times. A link is a recommendation: one from a page that many others recommend says more than one from a page nobody links to, which is why search engines weigh links by the importance of the page they come from, and compute that importance the same way, over and over, until it settles.
9.6 Problem: Handshakes across Brenmoor
Problem 9.1
Weekend problem — how far apart the people of the largest group are
The program exercises/handshakes.py uses the given functions to compute the radius, the diameter and the centre of the largest component of the friendship graph, then again with one edge removed.
Part I — The graph.
- How many vertices and edges has the friendship graph? Check the sum of the degrees.
- Which people have the most friends? Which have exactly one?
- How many vertices have an odd degree? Is that consistent with Exercise 9.12?
- Give the neighbours of person .
Part II — Components.
- List the sizes of the components.
- Can the rumour, started by person , reach person ? Why?
- Which four edges join two of the three groups of numbers? Which of them join two components?
- How many edges, at least, would make the whole graph connected?
Part III — Eccentricities.
- Using the output of the distance listing, give the eccentricity of person .
- Find two people at distance from each other, and a shortest path between them.
- Which people are at distance from person ?
- How many days does the rumour take from person ?
Part IV — The centre, and a missing bridge.
- Give the radius, the diameter and the centre of the largest component. Check .
- Run the program. What happens to the components, the radius and the diameter when the friendship – ends?
- Why does the centre move to and ?
- Why does removing – change nothing, while removing – does?
- What does removing – do?
- If the library could ask one person to spread its news, whom should it ask, and how many days would the news take to reach the people?
- State the result: the diameter of the largest component, its centre, and what the loss of the friendship between the two central people does to the diameter.
Solution
Solution of Problem 9.1.
1. vertices and edges; the degrees add up to .
2. Most friends, : persons , , and . Exactly one: , , , , , , , , and .
3. Degrees , and : people, an even number, as the exercise proves.
4. , , , and .
5. , and .
6. No: person is in the component of people, and no path joins it to the component of person .
7. –, –, – and –. None joins two components: and have all their friends in the largest component.
8. : one edge joining the component of people to the largest one, and one joining person .
9. : the farthest people, , and , are at distance .
10. For example and : –––––––, seven edges.
11. , and .
12. Person has eccentricity : days.
13. Radius , diameter , centre ; .
14. The components stay , and , but the radius becomes and the diameter .
15. Without –, the two halves of the component are joined only through –; the people at the middle of that new route, and , become the closest to everyone.
16. Without –, the shortest paths still go through –, which is shorter: no distance that matters changes. Without –, every path between the two halves makes the detour through –.
17. Persons and become a component of their own: the largest component has people, with the same radius and diameter.
18. Person or person : the news reaches all people in days.
19. The largest friendship component of Brenmoor has people, diameter , radius and centre . If the friendship between the two central people, and , ends, the component stays in one piece but its diameter grows from to .