---
title: "Graphs: Networks of Roads and People"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 9
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 9 — Graphs: 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](#def-g10-graphs-first-look-graph)*, stores it in Python, measures [distances](#def-g10-graphs-first-look-distance) in it, and finds its [centre](#def-g10-graphs-first-look-eccentricity).

**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](#def-g10-graphs-first-look-graph) of Brenmoor the [vertices](#def-g10-graphs-first-look-graph) are the people $1$ to $40$, and an [edge](#def-g10-graphs-first-look-graph) joins two friends. In the road [graph](#def-g10-graphs-first-look-graph) the [vertices](#def-g10-graphs-first-look-graph) are the $30$ places, and an [edge](#def-g10-graphs-first-look-graph) is a road.

**Definition 9.2 (Degree, neighbour).**

The *neighbours* of a [vertex](#def-g10-graphs-first-look-graph) are the [vertices](#def-g10-graphs-first-look-graph) adjacent to it. Its *degree* is the number of its neighbours.

**Definition 9.3 (Directed graph, weighted graph).**

In a *directed graph* each [edge](#def-g10-graphs-first-look-graph) goes from one [vertex](#def-g10-graphs-first-look-graph) to another, like a one-way street: an [edge](#def-g10-graphs-first-look-graph) from $a$ to $b$ does not let you go from $b$ to $a$. A [vertex](#def-g10-graphs-first-look-graph) then has an *[out-degree](#def-g10-graphs-first-look-degree)*, the number of [edges](#def-g10-graphs-first-look-graph) leaving it, and an *[in-degree](#def-g10-graphs-first-look-degree)*, the number of [edges](#def-g10-graphs-first-look-graph) arriving. In a *weighted graph* each [edge](#def-g10-graphs-first-look-graph) carries a number, its *weight*: a [length](#def-g10-graphs-first-look-path) in metres, a time, a price.

![The same four vertices and four edges, as an undirected graph, a directed graph and a weighted graph.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-graphs-first-look/fig-f46127f1d264.svg)

*The same four [vertices](#def-g10-graphs-first-look-graph) and four [edges](#def-g10-graphs-first-look-graph), as an undirected [graph](#def-g10-graphs-first-look-graph), a [directed graph](#def-g10-graphs-first-look-directed) and a [weighted graph](#def-g10-graphs-first-look-directed).*

## 9.2 A graph in Python

A [graph](#def-g10-graphs-first-look-graph) is stored as a dictionary from each [vertex](#def-g10-graphs-first-look-graph) to the set of its [neighbours](#def-g10-graphs-first-look-degree). An undirected [edge](#def-g10-graphs-first-look-graph) is written at both of its ends; a [vertex](#def-g10-graphs-first-look-graph) without any [edge](#def-g10-graphs-first-look-graph) still gets an empty set, so that it is not forgotten.

```python
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]])
```

***Listing 9.1.** The friendship [graph](#def-g10-graphs-first-look-graph) as a dictionary of sets. code/grade-10/09-graphs-first-look/listings/load_friends.py*

```
$ 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]
```

***Output 9.1.** Person $40$ is a [vertex](#def-g10-graphs-first-look-graph) with no [edge](#def-g10-graphs-first-look-graph).*

```python
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())])
```

***Listing 9.2.** How many people have each number of friends. code/grade-10/09-graphs-first-look/listings/degree_table.py*

```
$ 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]
```

***Output 9.2.** The [degrees](#def-g10-graphs-first-look-degree) add up to $100$, twice the $50$ friendships.*

**Proposition 9.4 (Sum of the degrees).**

In an undirected [graph](#def-g10-graphs-first-look-graph), the sum of the [degrees](#def-g10-graphs-first-look-degree) of the [vertices](#def-g10-graphs-first-look-graph) is twice the number of [edges](#def-g10-graphs-first-look-graph).

The proof is [Exercise 9.12](#exo-g10-graphs-first-look-12). A road [graph](#def-g10-graphs-first-look-graph) needs weights, and one-way roads make it directed: the listing stores a dictionary of [neighbours](#def-g10-graphs-first-look-degree) with their [distances](#def-g10-graphs-first-look-distance), and writes a two-way road as two directed [edges](#def-g10-graphs-first-look-graph).

```python
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])
```

***Listing 9.3.** The road [graph](#def-g10-graphs-first-look-graph), directed and weighted. code/grade-10/09-graphs-first-look/listings/load_roads.py*

```
$ 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}
```

***Output 9.3.** $53$ roads give $105$ directed [edges](#def-g10-graphs-first-look-graph): one road, from the Town Square to the Library, is one-way.*

A program that builds a [graph](#def-g10-graphs-first-look-graph) by hand can forget one end of an [edge](#def-g10-graphs-first-look-graph). The check is short: every [edge](#def-g10-graphs-first-look-graph) must have its reverse, except the one-way roads.

```python
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")))
```

***Listing 9.4.** Finding the [edges](#def-g10-graphs-first-look-graph) without a reverse. code/grade-10/09-graphs-first-look/listings/check_symmetric.py*

```
$ python check_symmetric.py
friendships: []
roads:       [(1, 3)]
```

***Output 9.4.** The friendships are symmetric; among the roads, only road $1$ is not.*

## 9.3 Paths and distance

**Definition 9.5 (Path, length of a path).**

A *path* is a sequence of [vertices](#def-g10-graphs-first-look-graph) in which each one is adjacent to the next (in a [directed graph](#def-g10-graphs-first-look-directed), joined by an [edge](#def-g10-graphs-first-look-graph) going from it to the next). Its *length* is its number of [edges](#def-g10-graphs-first-look-graph), or, in a [weighted graph](#def-g10-graphs-first-look-directed), the sum of the weights of its [edges](#def-g10-graphs-first-look-graph).

**Definition 9.6 (Distance).**

The *distance* from a [vertex](#def-g10-graphs-first-look-graph) $a$ to a [vertex](#def-g10-graphs-first-look-graph) $b$ is the [length](#def-g10-graphs-first-look-path) of a shortest [path](#def-g10-graphs-first-look-path) from $a$ to $b$. If there is no such [path](#def-g10-graphs-first-look-path), there is no distance.

**Definition 9.7 (Connected graph, component).**

An undirected [graph](#def-g10-graphs-first-look-graph) is *connected* if there is a [path](#def-g10-graphs-first-look-path) between any two of its [vertices](#def-g10-graphs-first-look-graph). A *connected component* is a largest set of [vertices](#def-g10-graphs-first-look-graph) joined to one another by [paths](#def-g10-graphs-first-look-path).

Computing [distances](#def-g10-graphs-first-look-distance) in a large [graph](#def-g10-graphs-first-look-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](#def-g10-graphs-first-look-distance), in [edges](#def-g10-graphs-first-look-graph), from `a` to every [vertex](#def-g10-graphs-first-look-graph) it can reach, and `components(g)` returns the components, largest first.

```python
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))
```

***Listing 9.5.** The components of the friendship [graph](#def-g10-graphs-first-look-graph). code/grade-10/09-graphs-first-look/listings/components.py*

```
$ 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
```

***Output 9.5.** Three components: $29$ people, $10$ people, and person $40$ alone.*

![The friendship graph of people 1 to 40, drawn in three groups by number. The orange edges join two groups. Persons 1 and 28, shaded, are the centre of the largest component; the group on the right is a component of its own, except 18, 20 and 25, whose friends are elsewhere.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-graphs-first-look/fig-253a5ff9ab0a.svg)

*The friendship [graph](#def-g10-graphs-first-look-graph) of people $1$ to $40$, drawn in three groups by number. The orange [edges](#def-g10-graphs-first-look-graph) join two groups. Persons $1$ and $28$, shaded, are the [centre](#def-g10-graphs-first-look-eccentricity) of the largest component; the group on the right is a component of its own, except $18$, $20$ and $25$, whose friends are elsewhere.*

On a small weighted map, a shortest route can be found by hand with a *frontier*: keep the [distance](#def-g10-graphs-first-look-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.

![Part of the town’s road map, lengths in metres, from the Library (3) to the North Bridge (23). The route 3–24–1–23 is 3840 m. The road from the Town Square (1) to the Library is one-way, so the way back, 23–1–3, is only 2570 m.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-graphs-first-look/fig-7ee77fff9635.svg)

*Part of the town’s road map, [lengths](#def-g10-graphs-first-look-path) in metres, from the Library (3) to the North Bridge (23). The route 3–24–1–23 is $3840$ m. The road from the Town Square (1) to the Library is one-way, so the way back, 23–1–3, is only $2570$ m.*

## 9.4 Radius, diameter and centre

**Definition 9.8 (Eccentricity, radius, diameter, centre).**

In a [connected graph](#def-g10-graphs-first-look-connected), the *eccentricity* of a [vertex](#def-g10-graphs-first-look-graph) is its largest [distance](#def-g10-graphs-first-look-distance) to another [vertex](#def-g10-graphs-first-look-graph). The *radius* of the [graph](#def-g10-graphs-first-look-graph) is the smallest eccentricity, its *diameter* the largest one, and its *centre* the set of the [vertices](#def-g10-graphs-first-look-graph) whose eccentricity is the radius.

![Each vertex with its eccentricity. The radius is 2, the diameter 4, and the centre is C alone: from C, every vertex is at most two edges away.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-graphs-first-look/fig-b6418499dcdf.svg)

*Each [vertex](#def-g10-graphs-first-look-graph) with its [eccentricity](#def-g10-graphs-first-look-eccentricity). The [radius](#def-g10-graphs-first-look-eccentricity) is $2$, the [diameter](#def-g10-graphs-first-look-eccentricity) $4$, and the [centre](#def-g10-graphs-first-look-eccentricity) is C alone: from C, every [vertex](#def-g10-graphs-first-look-graph) is at most two [edges](#def-g10-graphs-first-look-graph) away.*

The rumour of the opening question is a question about [eccentricity](#def-g10-graphs-first-look-eccentricity): started by a person of [eccentricity](#def-g10-graphs-first-look-eccentricity) $e$, it reaches everyone in that person’s component after $e$ days. On the largest component of the friendship [graph](#def-g10-graphs-first-look-graph):

```python
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])
```

***Listing 9.6.** [Distances](#def-g10-graphs-first-look-distance) from person $1$, then the [radius](#def-g10-graphs-first-look-eccentricity), [diameter](#def-g10-graphs-first-look-eccentricity) and [centre](#def-g10-graphs-first-look-eccentricity). code/grade-10/09-graphs-first-look/listings/distances_given.py*

```
$ 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]
```

***Output 9.6.** Persons $1$ and $28$ reach the whole component in $4$ days; from the worst place it takes $7$.*

**Remark 9.9.**

$29$ people, each with at most $5$ friends, and yet everyone is within $7$ steps of everyone in the component. In large networks of people the [distances](#def-g10-graphs-first-look-distance) are surprisingly small, a property called the *small world*: even with a few friends each, the number of people within $k$ steps multiplies at each step, so it grows very fast with $k$.

**Method 9.10 (Finding the centre of a small graph by hand).**

1. For each [vertex](#def-g10-graphs-first-look-graph) , write the [distance](#def-g10-graphs-first-look-distance) to every other [vertex](#def-g10-graphs-first-look-graph) , by layers: its [neighbours](#def-g10-graphs-first-look-degree) at $1$ , their new [neighbours](#def-g10-graphs-first-look-degree) at $2$ , and so on.
2. Its [eccentricity](#def-g10-graphs-first-look-eccentricity) is the number of the last layer.
3. The [radius](#def-g10-graphs-first-look-eccentricity) is the smallest [eccentricity](#def-g10-graphs-first-look-eccentricity) , the [diameter](#def-g10-graphs-first-look-eccentricity) the largest; the [centre](#def-g10-graphs-first-look-eccentricity) is the [vertices](#def-g10-graphs-first-look-graph) of [eccentricity](#def-g10-graphs-first-look-eccentricity) equal to the [radius](#def-g10-graphs-first-look-eccentricity) .

A map application turns a satellite position into a [vertex](#def-g10-graphs-first-look-graph) of the road [graph](#def-g10-graphs-first-look-graph), and a route into a shortest [path](#def-g10-graphs-first-look-path). The receiver gives its position as text, in a standard sentence format: [Exercise 9.11](#exo-g10-graphs-first-look-11) decodes one.

## 9.5 Exercises

**Exercise 9.1 ★.**

A [graph](#def-g10-graphs-first-look-graph) has $5$ [vertices](#def-g10-graphs-first-look-graph) with [degrees](#def-g10-graphs-first-look-degree) $3$, $2$, $2$, $2$ and $1$. How many [edges](#def-g10-graphs-first-look-graph) does it have? Can a [graph](#def-g10-graphs-first-look-graph) have [degrees](#def-g10-graphs-first-look-degree) $3$, $3$, $1$?

**Solution of Exercise 9.1.**

The [degrees](#def-g10-graphs-first-look-degree) add up to $3 + 2 + 2 + 2 + 1 = 10$, twice the number of [edges](#def-g10-graphs-first-look-graph): $5$ [edges](#def-g10-graphs-first-look-graph). [Degrees](#def-g10-graphs-first-look-degree) $3$, $3$, $1$ add up to $7$, an odd number, which cannot be twice a number of [edges](#def-g10-graphs-first-look-graph); besides, with $3$ [vertices](#def-g10-graphs-first-look-graph) a [degree](#def-g10-graphs-first-look-degree) is at most $2$.

**Exercise 9.2 ★.**

Write the dictionary of sets of the undirected [graph](#def-g10-graphs-first-look-graph) of the first drawing of the chapter ([vertices](#def-g10-graphs-first-look-graph) A, B, C, D).

**Solution of Exercise 9.2.**

`{"A": {"B", "C"}, "B": {"A", "C", "D"}, "C": {"A", "B"}, "D": {"B"}}`: each of the four [edges](#def-g10-graphs-first-look-graph) appears twice.

**Exercise 9.3 ★.**

In the [graph](#def-g10-graphs-first-look-graph) of eccentricities, give the [distance](#def-g10-graphs-first-look-distance) from A to G and from E to F. Give two different shortest [paths](#def-g10-graphs-first-look-path) from B to D, or explain why there is only one.

**Solution of Exercise 9.3.**

A to G: A–B–C–F–G, [distance](#def-g10-graphs-first-look-distance) $4$. E to F: E–D–C–F, [distance](#def-g10-graphs-first-look-distance) $3$. From B to D there is only B–C–D: the [graph](#def-g10-graphs-first-look-graph) has no cycle, so between two [vertices](#def-g10-graphs-first-look-graph) there is a single [path](#def-g10-graphs-first-look-path) that does not repeat a [vertex](#def-g10-graphs-first-look-graph).

**Exercise 9.4 ★.**

A [graph](#def-g10-graphs-first-look-graph) has the [edges](#def-g10-graphs-first-look-graph) $1$–$2$, $2$–$3$, $4$–$5$ and the [vertices](#def-g10-graphs-first-look-graph) $1$ to $6$. List its components. How many [edges](#def-g10-graphs-first-look-graph) would make it [connected](#def-g10-graphs-first-look-connected), at least?

**Solution of Exercise 9.4.**

$\{1, 2, 3\}$, $\{4, 5\}$ and $\{6\}$. Each new [edge](#def-g10-graphs-first-look-graph) joins at most two components into one, so going from $3$ components to $1$ takes at least $2$ [edges](#def-g10-graphs-first-look-graph), for example $3$–$4$ and $5$–$6$.

**Exercise 9.5 ★.**

Write `degree(g, v)`, and use it to print the people of the friendship [graph](#def-g10-graphs-first-look-graph) whose [degree](#def-g10-graphs-first-look-degree) is $1$.

**Solution of Exercise 9.5.**

`return len(g[v])` (`exercises/graph_tools.py`). The people of [degree](#def-g10-graphs-first-look-degree) $1$ are $4$, $15$, $18$, $21$, $22$, $24$, $25$, $26$, $31$ and $35$: the ten of the [degree](#def-g10-graphs-first-look-degree) table.

**Exercise 9.6 ★★.**

A function `add_friendship(g, a, b)` only writes `g[a].add(b)`. After building the [graph](#def-g10-graphs-first-look-graph) with it, which listing of the chapter detects the problem, and what does it print? Correct the function.

**Solution of Exercise 9.6.**

Each friendship is stored only at its first person, so the check of symmetry prints all $50$ friendships as [edges](#def-g10-graphs-first-look-graph) 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](#def-g10-graphs-first-look-graph) is a [path](#def-g10-graphs-first-look-path) of `g`. Check that `[3, 2, 10, 1, 28]` is a [path](#def-g10-graphs-first-look-path) of the friendship [graph](#def-g10-graphs-first-look-graph) and `[3, 1]` is not.

**Solution of Exercise 9.7.**

Return `False` for an empty list or a first [vertex](#def-g10-graphs-first-look-graph) outside the [graph](#def-g10-graphs-first-look-graph); otherwise check that every [vertex](#def-g10-graphs-first-look-graph) but the last has the next one among its [neighbours](#def-g10-graphs-first-look-degree): `all(seq[i + 1] in g[seq[i]] for i in range(len(seq) - 1))` (`exercises/graph_tools.py`). $3$–$2$, $2$–$10$, $10$–$1$ and $1$–$28$ are friendships; $3$–$1$ is not.

**Exercise 9.8 ★★.**

Draw the [graph](#def-g10-graphs-first-look-graph) with [edges](#def-g10-graphs-first-look-graph) $1$–$2$, $2$–$3$, $3$–$4$, $4$–$1$, $1$–$5$. Give the [eccentricity](#def-g10-graphs-first-look-eccentricity) of each [vertex](#def-g10-graphs-first-look-graph), the [radius](#def-g10-graphs-first-look-eccentricity), the [diameter](#def-g10-graphs-first-look-eccentricity) and the [centre](#def-g10-graphs-first-look-eccentricity).

**Solution of Exercise 9.8.**

Eccentricities: $1$: $2$, $2$: $2$, $3$: $3$, $4$: $2$, $5$: $3$ (the farthest pair is $3$ and $5$, through $2$ or $4$ and then $1$). [Radius](#def-g10-graphs-first-look-eccentricity) $2$, [diameter](#def-g10-graphs-first-look-eccentricity) $3$, [centre](#def-g10-graphs-first-look-eccentricity) $\{1, 2, 4\}$.

**Exercise 9.9 ★★.**

In the directed drawing of the chapter, give the [in-degree](#def-g10-graphs-first-look-degree) and [out-degree](#def-g10-graphs-first-look-degree) of every [vertex](#def-g10-graphs-first-look-graph). Check that the [in-degrees](#def-g10-graphs-first-look-degree) and the [out-degrees](#def-g10-graphs-first-look-degree) have the same sum, and say why that is always so.

**Solution of Exercise 9.9.**

A: in $1$, out $1$; B: in $1$, out $2$; C: in $1$, out $1$; D: in $1$, out $0$. Both sums are $4$, the number of [edges](#def-g10-graphs-first-look-graph): every directed [edge](#def-g10-graphs-first-look-graph) leaves exactly one [vertex](#def-g10-graphs-first-look-graph) and arrives at exactly one.

**Exercise 9.10 ★★.**

Write `edges_from_dict(g)`, which returns the set of the [edges](#def-g10-graphs-first-look-graph) of an undirected [graph](#def-g10-graphs-first-look-graph), each written once as a pair (smaller, larger). Check the sum of the [degrees](#def-g10-graphs-first-look-degree) on the friendship [graph](#def-g10-graphs-first-look-graph).

**Solution of Exercise 9.10.**

`return {(min(a, b), max(a, b)) for a in g for b in g[a]}`: each [edge](#def-g10-graphs-first-look-graph) is met twice, once from each end, and the set keeps it once (`exercises/graph_tools.py`). The friendship [graph](#def-g10-graphs-first-look-graph) gives $50$ [edges](#def-g10-graphs-first-look-graph), and the [degrees](#def-g10-graphs-first-look-degree) add up to $100$.

**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 of Exercise 9.11.**

The time is 09:30:15 (on the satellites’ universal time). Latitude: $48 + 7.0381/60 \approx 48.11730$ [degrees](#def-g10-graphs-first-look-degree) north. Longitude: $1 + 31.5240/60 = 1.52540$ [degrees](#def-g10-graphs-first-look-degree) west, so $-1.52540$ (`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](#def-g10-graphs-first-look-graph) the sum of the [degrees](#def-g10-graphs-first-look-degree) is twice the number of [edges](#def-g10-graphs-first-look-graph). Deduce that the number of [vertices](#def-g10-graphs-first-look-graph) of odd [degree](#def-g10-graphs-first-look-degree) is even.

**Solution of Exercise 9.12.**

Count the pairs ([vertex](#def-g10-graphs-first-look-graph), [edge](#def-g10-graphs-first-look-graph)) where the [edge](#def-g10-graphs-first-look-graph) touches the [vertex](#def-g10-graphs-first-look-graph). Counted by [vertex](#def-g10-graphs-first-look-graph), each [vertex](#def-g10-graphs-first-look-graph) $v$ is in $\deg(v)$ pairs, which gives the sum of the [degrees](#def-g10-graphs-first-look-degree). Counted by [edge](#def-g10-graphs-first-look-graph), each [edge](#def-g10-graphs-first-look-graph) touches exactly two [vertices](#def-g10-graphs-first-look-graph), which gives $2|E|$. So the sum of the [degrees](#def-g10-graphs-first-look-degree) is $2|E|$, an even number; the [vertices](#def-g10-graphs-first-look-graph) of even [degree](#def-g10-graphs-first-look-degree) add an even amount, so the odd [degrees](#def-g10-graphs-first-look-degree) 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](#def-g10-graphs-first-look-connected), $\text{radius} \le \text{diameter} \le 2 \times \text{radius}$. For the second inequality, take a [vertex](#def-g10-graphs-first-look-graph) $c$ of the [centre](#def-g10-graphs-first-look-eccentricity) and two [vertices](#def-g10-graphs-first-look-graph) $a$ and $b$, and go from $a$ to $b$ through $c$.

**Solution of Exercise 9.13.**

The [radius](#def-g10-graphs-first-look-eccentricity) is the smallest [eccentricity](#def-g10-graphs-first-look-eccentricity) and the [diameter](#def-g10-graphs-first-look-eccentricity) the largest, so $\text{radius} \le \text{diameter}$. Take $c$ in the [centre](#def-g10-graphs-first-look-eccentricity) and any two [vertices](#def-g10-graphs-first-look-graph) $a$ and $b$. A [path](#def-g10-graphs-first-look-path) from $a$ to $c$ followed by a [path](#def-g10-graphs-first-look-path) from $c$ to $b$ is a [path](#def-g10-graphs-first-look-path) from $a$ to $b$ (it may be shortened if it repeats a [vertex](#def-g10-graphs-first-look-graph)), so $d(a, b) \le d(a, c) + d(c, b) \le \text{radius} + \text{radius}$. This holds for every pair, so the [diameter](#def-g10-graphs-first-look-eccentricity) is at most $2 \times \text{radius}$. The [graph](#def-g10-graphs-first-look-graph) of eccentricities reaches it: [radius](#def-g10-graphs-first-look-eccentricity) $2$, [diameter](#def-g10-graphs-first-look-eccentricity) $4$.

**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](#def-g10-graphs-first-look-graph) count each triangle three times? How many triangles has the friendship [graph](#def-g10-graphs-first-look-graph)?

**Solution of Exercise 9.14.**

`common_friends` returns `g[a] & g[b]`. A triangle $\{x, y, z\}$ is found from its [edge](#def-g10-graphs-first-look-graph) $x$–$y$ (common friend $z$), from $x$–$z$ (common friend $y$) and from $y$–$z$ (common friend $x$): three times, so the sum is divided by $3$ (`exercises/graph_tools.py`). The friendship [graph](#def-g10-graphs-first-look-graph) has $2$ triangles.

**Exercise 9.15 ★★★.**

A tiny web has five pages, P1 to P5, and links P1$\to$P2, P1$\to$P3, P2$\to$P3, P4$\to$P3, P5$\to$P4, P3$\to$P1. Rank the pages by [in-degree](#def-g10-graphs-first-look-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 of Exercise 9.15.**

[In-degrees](#def-g10-graphs-first-look-degree): P3 has $3$, P1, P2 and P4 have $1$, P5 has $0$. Votes: P1 gives $\tfrac12$ to P2 and $\tfrac12$ to P3; P2, P4 and P3 give their whole vote to P3, P3 and P1; P5 gives its vote to P4. Totals: P3 $2.5$, P1 $1$, P4 $1$, P2 $0.5$, P5 $0$. 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](#def-g10-graphs-first-look-eccentricity), the [diameter](#def-g10-graphs-first-look-eccentricity) and the [centre](#def-g10-graphs-first-look-eccentricity) of the largest component of the friendship [graph](#def-g10-graphs-first-look-graph), then again with one [edge](#def-g10-graphs-first-look-graph) removed.

**Part I — The graph.**

1. How many [vertices](#def-g10-graphs-first-look-graph) and [edges](#def-g10-graphs-first-look-graph) has the friendship [graph](#def-g10-graphs-first-look-graph) ? Check the sum of the [degrees](#def-g10-graphs-first-look-degree) .
2. Which people have the most friends? Which have exactly one?
3. How many [vertices](#def-g10-graphs-first-look-graph) have an odd [degree](#def-g10-graphs-first-look-degree) ? Is that consistent with [Exercise 9.12](#exo-g10-graphs-first-look-12) ?
4. Give the [neighbours](#def-g10-graphs-first-look-degree) of person $28$ .

**Part II — Components.**

5. List the sizes of the components.
6. Can the rumour, started by person $1$ , reach person $23$ ? Why?
7. Which four [edges](#def-g10-graphs-first-look-graph) join two of the three groups of numbers? Which of them join two components?
8. How many [edges](#def-g10-graphs-first-look-graph) , at least, would make the whole [graph](#def-g10-graphs-first-look-graph) [connected](#def-g10-graphs-first-look-connected) ?

**Part III — Eccentricities.**

9. Using the output of the [distance](#def-g10-graphs-first-look-distance) listing, give the [eccentricity](#def-g10-graphs-first-look-eccentricity) of person $1$ .
10. Find two people at [distance](#def-g10-graphs-first-look-distance) $7$ from each other, and a shortest [path](#def-g10-graphs-first-look-path) between them.
11. Which people are at [distance](#def-g10-graphs-first-look-distance) $4$ from person $1$ ?
12. How many days does the rumour take from person $3$ ?

**Part IV — The centre, and a missing bridge.**

13. Give the [radius](#def-g10-graphs-first-look-eccentricity) , the [diameter](#def-g10-graphs-first-look-eccentricity) and the [centre](#def-g10-graphs-first-look-eccentricity) of the largest component. Check $\text{radius} \le \text{diameter} \le 2 \times \text{radius}$ .
14. Run the program. What happens to the components, the [radius](#def-g10-graphs-first-look-eccentricity) and the [diameter](#def-g10-graphs-first-look-eccentricity) when the friendship $1$ – $28$ ends?
15. Why does the [centre](#def-g10-graphs-first-look-eccentricity) move to $5$ and $37$ ?
16. Why does removing $5$ – $37$ change nothing, while removing $1$ – $28$ does?
17. What does removing $12$ – $20$ do?
18. 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 $29$ people?
19. State the result: the [diameter](#def-g10-graphs-first-look-eccentricity) of the largest component, its [centre](#def-g10-graphs-first-look-eccentricity) , and what the loss of the friendship between the two central people does to the [diameter](#def-g10-graphs-first-look-eccentricity) .

**Solution of Problem 9.1.**

**1.** $40$ [vertices](#def-g10-graphs-first-look-graph) and $50$ [edges](#def-g10-graphs-first-look-graph); the [degrees](#def-g10-graphs-first-look-degree) add up to $100 = 2 \times 50$.

**2.** Most friends, $5$: persons $1$, $12$, $23$ and $28$. Exactly one: $4$, $15$, $18$, $21$, $22$, $24$, $25$, $26$, $31$ and $35$.

**3.** [Degrees](#def-g10-graphs-first-look-degree) $1$, $3$ and $5$: $10 + 10 + 4 = 24$ people, an even number, as the exercise proves.

**4.** $1$, $34$, $36$, $37$ and $39$.

**5.** $29$, $10$ and $1$.

**6.** No: person $23$ is in the component of $10$ people, and no [path](#def-g10-graphs-first-look-path) joins it to the component of person $1$.

**7.** $1$–$28$, $5$–$37$, $12$–$20$ and $25$–$37$. None joins two components: $20$ and $25$ have all their friends in the largest component.

**8.** $2$: one [edge](#def-g10-graphs-first-look-graph) joining the component of $10$ people to the largest one, and one joining person $40$.

**9.** $4$: the farthest people, $31$, $35$ and $38$, are at [distance](#def-g10-graphs-first-look-distance) $4$.

**10.** For example $3$ and $31$: $3$–$2$–$10$–$1$–$28$–$34$–$29$–$31$, seven [edges](#def-g10-graphs-first-look-graph).

**11.** $31$, $35$ and $38$.

**12.** Person $3$ has [eccentricity](#def-g10-graphs-first-look-eccentricity) $7$: $7$ days.

**13.** [Radius](#def-g10-graphs-first-look-eccentricity) $4$, [diameter](#def-g10-graphs-first-look-eccentricity) $7$, [centre](#def-g10-graphs-first-look-eccentricity) $\{1, 28\}$; $4 \le 7 \le 8$.

**14.** The components stay $29$, $10$ and $1$, but the [radius](#def-g10-graphs-first-look-eccentricity) becomes $5$ and the [diameter](#def-g10-graphs-first-look-eccentricity) $9$.

**15.** Without $1$–$28$, the two halves of the component are joined only through $5$–$37$; the people at the middle of that new route, $5$ and $37$, become the closest to everyone.

**16.** Without $5$–$37$, the shortest [paths](#def-g10-graphs-first-look-path) still go through $1$–$28$, which is shorter: no [distance](#def-g10-graphs-first-look-distance) that matters changes. Without $1$–$28$, every [path](#def-g10-graphs-first-look-path) between the two halves makes the detour through $5$–$37$.

**17.** Persons $18$ and $20$ become a component of their own: the largest component has $27$ people, with the same [radius](#def-g10-graphs-first-look-eccentricity) and [diameter](#def-g10-graphs-first-look-eccentricity).

**18.** Person $1$ or person $28$: the news reaches all $29$ people in $4$ days.

**19.** The largest friendship component of Brenmoor has $29$ people, [diameter](#def-g10-graphs-first-look-eccentricity) $7$, [radius](#def-g10-graphs-first-look-eccentricity) $4$ and [centre](#def-g10-graphs-first-look-eccentricity) $\{1, 28\}$. If the friendship between the two central people, $1$ and $28$, ends, the component stays in one piece but its [diameter](#def-g10-graphs-first-look-eccentricity) grows from $7$ to $9$.
