Ciência da computação · Livro 2 · 10.º ao 12.º ano

High School Computer Science

Este livro ainda não está disponível em Português. Edições: English.

High School Computer Science · 10.º ao 12.º ano

35Project: A Route Planner

A route planner answers one question: what is the fastest way from here to there? Behind the question sit three pieces of this year’s work. The map is data, kept in a database; the roads form a graph; and the answer is a shortest path, found by Dijkstra’s algorithm. This project joins the three into one program for the town of Brenmoor, the invented town of the series, with a class that hides how it works and a small text interface in front of it.

The question a route planner answers, asked the old way.
The question a route planner answers, asked the old way.

You already know

Tables, keys and SQL queries (chapter 30). Directed and weighted graphs (chapter 9), and Dijkstra’s algorithm with its parents (chapter 26). Classes, methods and interfaces (chapters 23 and 20). Test suites with unittest (chapter 1).

35.1 The specification

Write, in Python, a program that answers “fastest route from place AA to place BB” in Brenmoor. The places and roads are stored in an SQLite database with keys and integrity constraints, filled from the town’s tables. They are loaded into a directed graph whose arcs carry the travel time in seconds, computed from the length of each road and its speed limit; a one-way road gives a single arc. Dijkstra’s algorithm returns the route and its time. A class RoutePlanner offers a documented interface: a route by time or by distance, a road closed and reopened, and an error for a place that does not exist. A text menu lets a person use it, and a test suite checks every function.

The work goes in five milestones, each one runnable before the next starts. The town’s tables are read with the series’ module town, which is imported and never changed.

The architecture. Each box is one module and one milestone; each arrow is the only way data passes from one module to the next. The interface never sees the database, and the algorithm never sees SQL.
The architecture. Each box is one module and one milestone; each arrow is the only way data passes from one module to the next. The interface never sees the database, and the algorithm never sees SQL.

35.2 Milestone 1: the database

The planner keeps its own two tables, place and road, with the constraints that make bad data impossible to store: every road starts and ends at a place that exists, has a positive length and a sensible speed limit, and does not join a place to itself; no two places share a name, since the interface finds places by name.

The schema of the planner’s database. Each road refers to two places through two foreign keys; the checks on the right are the integrity constraints that SQLite enforces at every insertion.
The schema of the planner’s database. Each road refers to two places through two foreign keys; the checks on the right are the integrity constraints that SQLite enforces at every insertion.
"""Milestone 1: the planner's database, with its keys and constraints."""
import sqlite3

import town

SCHEMA = """
CREATE TABLE place (
    place_id  INTEGER PRIMARY KEY,
    name      TEXT NOT NULL UNIQUE,
    kind      TEXT NOT NULL
);
CREATE TABLE road (
    road_id    INTEGER PRIMARY KEY,
    from_place INTEGER NOT NULL REFERENCES place(place_id),
    to_place   INTEGER NOT NULL REFERENCES place(place_id),
    length_m   INTEGER NOT NULL CHECK (length_m > 0),
    speed_kmh  INTEGER NOT NULL CHECK (speed_kmh BETWEEN 10 AND 130),
    one_way    INTEGER NOT NULL CHECK (one_way IN (0, 1)),
    CHECK (from_place <> to_place)
);
"""


def build():
    """A new in-memory database filled from the town's places and roads."""
    conn = sqlite3.connect(":memory:")
    conn.execute("PRAGMA foreign_keys = ON")
    conn.executescript(SCHEMA)
    places = town.load("places")
    conn.executemany("INSERT INTO place VALUES (?, ?, ?)",
                     [(p["place_id"], p["name"], p["kind"]) for p in places])
    conn.executemany("INSERT INTO road VALUES (?, ?, ?, ?, ?, ?)",
                     [(r["road_id"], r["from_place"], r["to_place"], r["length_m"],
                       r["speed_kmh"], r["one_way"]) for r in town.load("roads")])
    conn.commit()
    return conn
Listing 35.1. Milestone 1: the schema, and a database filled from the town’s tables. code/grade-12/14-project-route-planner/listings/db.py

SQLite checks foreign keys only when asked, with PRAGMA foreign_keys = ON, once per connection. The first run counts the rows, shows the one-way road and the speed limits, and then tries three wrong insertions. One clause is new: GROUP BY speed_kmh splits the roads into one group per speed limit, and COUNT(*) then counts each group, so the query gives one row per group, not one per road.

import sqlite3

from db import build

conn = build()
for table in ["place", "road"]:
    print(table, conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0], "rows")
print("one-way:", conn.execute("SELECT road_id, from_place, to_place FROM road"
                               " WHERE one_way = 1").fetchall())
print("speeds:", conn.execute("SELECT speed_kmh, COUNT(*) FROM road"
                              " GROUP BY speed_kmh").fetchall())
TRIES = [("a road to place 99", "INSERT INTO road VALUES (54, 1, 99, 500, 50, 0)"),
         ("a negative length", "INSERT INTO road VALUES (54, 1, 2, -5, 50, 0)"),
         ("a second Station", "INSERT INTO place VALUES (31, 'Station', 'x')")]
for what, bad in TRIES:
    try:
        conn.execute(bad)
    except sqlite3.IntegrityError as e:
        print(f"refused, {what}: {e}")
Listing 35.2. Milestone 1: counting, and three insertions that the constraints must refuse. code/grade-12/14-project-route-planner/listings/run_m1.py
$ python run_m1.py
place 30 rows
road 53 rows
one-way: [(1, 1, 3)]
speeds: [(30, 20), (50, 21), (70, 12)]
refused, a road to place 99: FOREIGN KEY constraint failed
refused, a negative length: CHECK constraint failed: length_m > 0
refused, a second Station: UNIQUE constraint failed: place.name
Output 35.1. 3030 places, 5353 roads, one of them one-way; each wrong row is refused with the name of the rule it breaks.

The town’s own tables, places and roads, carry the same columns and the coordinates of each place in metres. Plain SQL already answers questions about the map, before any graph exists.

-- load: town
SELECT kind, COUNT(*) AS places FROM places GROUP BY kind ORDER BY places DESC, kind LIMIT 4;
SELECT r.road_id, a.name AS from_name, b.name AS to_name, r.length_m, r.speed_kmh
FROM roads AS r
  JOIN places AS a ON r.from_place = a.place_id
  JOIN places AS b ON r.to_place = b.place_id
ORDER BY r.length_m DESC LIMIT 3;
SELECT ROUND(SUM(length_m) / 1000.0, 2) AS km_of_road FROM roads;
Listing 35.3. Three questions to the town’s tables: the commonest kinds of place, the longest roads, and the total length. code/grade-12/14-project-route-planner/listings/queries.sql
$ python sqlrun.py queries.sql
sql> SELECT kind, COUNT(*) AS places FROM places GROUP BY kind ORDER BY places DESC, kind LIMIT 4;
+----------+--------+
| kind     | places |
+----------+--------+
| junction | 4      |
| park     | 3      |
| school   | 3      |
| shop     | 3      |
+----------+--------+
(4 rows)

sql> SELECT r.road_id, a.name AS from_name, b.name AS to_name, r.length_m, r.speed_kmh
...> FROM roads AS r
...>   JOIN places AS a ON r.from_place = a.place_id
...>   JOIN places AS b ON r.to_place = b.place_id
...> ORDER BY r.length_m DESC LIMIT 3;
+---------+---------------+---------------+----------+-----------+
| road_id | from_name     | to_name       | length_m | speed_kmh |
+---------+---------------+---------------+----------+-----------+
| 43      | Post Office   | Sports Hall   | 1830     | 30        |
| 9       | Library       | Garden Centre | 1790     | 70        |
| 21      | Swimming Pool | Bus Depot     | 1770     | 50        |
+---------+---------------+---------------+----------+-----------+
(3 rows)

sql> SELECT ROUND(SUM(length_m) / 1000.0, 2) AS km_of_road FROM roads;
+------------+
| km_of_road |
+------------+
| 61.14      |
+------------+
(1 row)
Output 35.2. The longest road, 18301830 metres, is also a slow one: 3030 km/h.

35.3 Milestone 2: the graph

The roads become arcs. A road of length ℓ\ell metres with a speed limit of vv km/h takes ℓ/(v/3.6)=3.6 ℓ/v\ell / (v / 3.6) = 3.6\, \ell / v seconds, since 11 km/h is 1000/36001000 / 3600 metres per second. The cost is rounded to the second, so that every time printed is a whole number.

"""Milestone 2: a directed graph whose arcs carry a cost, read from the database."""
from collections import deque


def travel_seconds(length_m, speed_kmh):
    """Time to drive a road at its speed limit, rounded to the second."""
    return round(length_m * 3.6 / speed_kmh)     # km/h to m/s: divide by 3.6


class Graph:
    def __init__(self):
        self.arcs = {}                           # vertex -> {successor: cost}

    def add_vertex(self, v):
        self.arcs.setdefault(v, {})

    def add_arc(self, u, v, cost):
        self.add_vertex(u)
        self.add_vertex(v)
        self.arcs[u][v] = cost

    def successors(self, u):
        return self.arcs[u].items()

    def arc_count(self):
        return sum(len(s) for s in self.arcs.values())

    def reachable(self, start):
        seen, queue = {start}, deque([start])
        while queue:
            for v in self.arcs[queue.popleft()]:
                if v not in seen:
                    seen.add(v)
                    queue.append(v)
        return seen
Listing 35.4. Milestone 2: the travel time of a road, and a class for a directed graph with costs. code/grade-12/14-project-route-planner/listings/graph.py

The class keeps a dictionary of dictionaries, the adjacency lists of chapter 26 with a cost on each arc. The method reachable is a breadth-first search: it checks that the town is connected, in the directed sense, from every place.

    def one_way_arcs(self):
        return [(u, v) for u in self.arcs for v in self.arcs[u]
                if u not in self.arcs[v]]


def from_database(conn, criterion="time", closed=()):
    """Arcs from the roads; a one-way road gives one arc, the others two."""
    g = Graph()
    for (p,) in conn.execute("SELECT place_id FROM place"):
        g.add_vertex(p)
    for road, a, b, length, speed, one_way in conn.execute("SELECT * FROM road"):
        if road in closed:
            continue
        cost = travel_seconds(length, speed) if criterion == "time" else length
        g.add_arc(a, b, cost)
        if not one_way:
            g.add_arc(b, a, cost)
    return g
Listing 35.5. Milestone 2: arcs without their reverse, and the graph read from the database, by time or by distance. code/grade-12/14-project-route-planner/listings/graph.py
from db import build
from graph import from_database, travel_seconds

conn = build()
g = from_database(conn)
print(len(g.arcs), "vertices,", g.arc_count(), "arcs")
print("road 2:", travel_seconds(1210, 50), "s for 1210 m at 50 km/h")
everyone = set(g.arcs)
print("every place reaches every place:",
      all(g.reachable(p) == everyone for p in g.arcs))
print("arcs without their reverse:", g.one_way_arcs())
print("from the Station (2):", dict(g.successors(2)))
Listing 35.6. Milestone 2: the checks of the graph. code/grade-12/14-project-route-planner/listings/run_m2.py
$ python run_m2.py
30 vertices, 105 arcs
road 2: 87 s for 1210 m at 50 km/h
every place reaches every place: True
arcs without their reverse: [(1, 3)]
from the Station (2): {9: 120, 10: 35, 11: 35}
Output 35.3. 2×52+1=1052 \times 52 + 1 = 105 arcs, every place reaches every other, and only the arc 1→31 \to 3 has no reverse.

The three successors of the Station show the point of travel times: River Park and Hill Park, at 680680 and 690690 metres on roads at 7070 km/h, are 3535 seconds away, while the Town Hall, at 10001000 metres on a road at 3030 km/h, is 120120 seconds away.

35.4 Milestone 3: shortest routes

Dijkstra’s algorithm, as in chapter 26, finishes at each step the unfinished vertex with the smallest tentative cost, found by a scan, and records the parent of each vertex it improves. Following the parents back from the target and reversing gives the route.

"""Milestones 3 and 4: shortest routes, and the planner that the interface uses."""
from db import build
from graph import from_database


def dijkstra(g, source):
    """Smallest cost from source to every vertex, and each vertex's parent."""
    dist, parent, done = {source: 0}, {source: None}, set()
    while len(done) < len(dist):
        u = min((v for v in dist if v not in done), key=dist.get)
        done.add(u)                              # dist[u] is now final
        for v, cost in g.successors(u):
            if v not in done and (v not in dist or dist[u] + cost < dist[v]):
                dist[v], parent[v] = dist[u] + cost, u
    return dist, parent


def rebuild(parent, target):
    path = []
    while target is not None:
        path.append(target)
        target = parent[target]
    return path[::-1]
Listing 35.7. Milestone 3: Dijkstra’s algorithm on a Graph, and the route rebuilt from the parents. code/grade-12/14-project-route-planner/listings/planner.py

The class of the next milestone wraps these two functions; the first run uses it already, to compare the two criteria and the two directions of the one-way road.

from planner import RoutePlanner

planner = RoutePlanner()
for start, end in [("Station", "Library"), ("Allotments", "Sports Hall")]:
    print(f"{start} to {end}:")
    for criterion in ["time", "distance"]:
        path, _ = planner.route(start, end, criterion)
        seconds = planner.cost_of(path, "time")
        metres = planner.cost_of(path, "distance")
        print(f"  by {criterion:8}: {seconds:>3} s {metres:>5} m  " + " > ".join(path))
there = planner.route("Town Square", "Library")[1]
back = planner.route("Library", "Town Square")[1]
print(f"Town Square to Library {there} s, back {back} s (road 1 is one-way)")
Listing 35.8. Milestone 3: by time and by distance, and both ways between the Town Square and the Library. code/grade-12/14-project-route-planner/listings/run_m3.py
$ python run_m3.py
Station to Library:
  by time    : 276 s  4330 m  Station > River Park > North Bridge > Town Square > Library
  by distance: 276 s  4330 m  Station > River Park > North Bridge > Town Square > Library
Allotments to Sports Hall:
  by time    :  71 s  1380 m  Allotments > College > Sports Hall
  by distance:  86 s  1200 m  Allotments > Sports Hall
Town Square to Library 98 s, back 204 s (road 1 is one-way)
Output 35.4. The two criteria can agree, or not: the shortest road from the Allotments is not the fastest.

From the Allotments to the Sports Hall the direct road is 12001200 metres at 5050 km/h, 8686 seconds; through the College it is 180180 metres longer, on two roads at 7070 km/h, and takes 7171 seconds. The criterion is part of the question: “shortest” and “fastest” are different graphs on the same roads. And the one-way road makes the town lopsided: 9898 seconds from the Town Square to the Library, 204204 seconds back, through the Garden Centre.

The town’s 53 roads (grey) drawn from the coordinates of the 30 places, numbered by their place_id, and in red the slowest of all fastest routes, from the Old Mill to the Post Office, as the planner computes it (figures/route_map.py).
The town’s 5353 roads (grey) drawn from the coordinates of the 3030 places, numbered by their place_id, and in red the slowest of all fastest routes, from the Old Mill to the Post Office, as the planner computes it (figures/route_map.py).

35.5 Milestone 4: the interface

The class RoutePlanner is what the rest of the program sees. Its user names places and roads; the identifiers, the graph and the algorithm stay inside. A wrong name raises ValueError with a message, so that the menu can say what went wrong instead of stopping.

class RoutePlanner:
    """Routes between the places of the town, by time (seconds) or by distance (m)."""

    def __init__(self, conn=None):
        self.conn = conn or build()
        self.names = dict(self.conn.execute("SELECT place_id, name FROM place"))
        self.ids = {name: p for p, name in self.names.items()}
        self.closed = set()

    def place_id(self, name):
        if name not in self.ids:
            raise ValueError(f"no place called {name!r}")
        return self.ids[name]

    def route(self, start, end, criterion="time"):
        """The best route as a list of names, and its total cost."""
        g = from_database(self.conn, criterion, self.closed)
        a, b = self.place_id(start), self.place_id(end)
        dist, parent = dijkstra(g, a)
        if b not in dist:
            raise ValueError(f"{end!r} cannot be reached from {start!r}")
        return [self.names[p] for p in rebuild(parent, b)], dist[b]

    def cost_of(self, path, criterion="time"):
        """The cost of a given route, as a list of names, by either criterion."""
        g = from_database(self.conn, criterion, self.closed)
        ids = [self.place_id(name) for name in path]
        return sum(g.arcs[a][b] for a, b in zip(ids, ids[1:]))

    def close_road(self, road_id):
        self.closed.add(road_id)

    def reopen_road(self, road_id):
        self.closed.discard(road_id)
Listing 35.9. Milestone 4: the class RoutePlanner and its five methods. code/grade-12/14-project-route-planner/listings/planner.py
The two classes: name, then attributes, then methods. RoutePlanner builds a Graph for each question, from the database and the set of closed roads, and passes it to dijkstra.
The two classes: name, then attributes, then methods. RoutePlanner builds a Graph for each question, from the database and the set of closed roads, and passes it to dijkstra.

Building the graph again for each question costs a few hundred operations here; it keeps the class simple, since a closed road then needs no change to any graph. Exercise 35.9 counts the cost of the whole town.

The menu reads a choice, then what that choice needs, and prints the answer in minutes and seconds. For the run below its input comes from the file menu.stdin, one line per answer: a route, a misspelt name, road 22 closed, the same route again, a wrong choice, and the end.

"""Milestone 4: a text interface to the planner."""
from planner import RoutePlanner


def minutes(seconds):
    return f"{seconds // 60} min {seconds % 60:02} s"


def main():
    planner = RoutePlanner()
    while True:
        choice = input("1 route, 2 places, 3 close a road, 4 quit: ").strip()
        if choice == "1":
            start, end = input("from: ").strip(), input("to: ").strip()
            try:
                path, seconds = planner.route(start, end)
            except ValueError as e:
                print("sorry:", e)
                continue
            roads = len(path) - 1
            print(minutes(seconds), "over", roads, "road" if roads == 1 else "roads")
            print("  " + " > ".join(path))
        elif choice == "2":
            print(", ".join(sorted(planner.ids)))
        elif choice == "3":
            planner.close_road(int(input("road number: ")))
            print("closed:", sorted(planner.closed))
        elif choice == "4":
            return
        else:
            print("please type 1, 2, 3 or 4")


main()
Listing 35.10. Milestone 4: the text interface. code/grade-12/14-project-route-planner/listings/menu.py
$ python menu.py
1 route, 2 places, 3 close a road, 4 quit: 1
from: Station
to: Library
4 min 36 s over 4 roads
  Station > River Park > North Bridge > Town Square > Library
1 route, 2 places, 3 close a road, 4 quit: 1
from: Station
to: Libary
sorry: no place called 'Libary'
1 route, 2 places, 3 close a road, 4 quit: 3
road number: 2
closed: [2]
1 route, 2 places, 3 close a road, 4 quit: 1
from: Station
to: Library
7 min 24 s over 7 roads
  Station > River Park > North Bridge > Swimming Pool > North School > Bus Depot > South Bridge > Library
1 route, 2 places, 3 close a road, 4 quit: 5
please type 1, 2, 3 or 4
1 route, 2 places, 3 close a road, 4 quit: 4
Output 35.5. A session with the input of menu.stdin; the misspelt name gets a message, and the closed road a longer route.

35.6 Milestone 5: tests and a measure

The tests check each layer: a travel time computed by hand, the arcs of the one-way road, the error for an unknown place, a route whose cost is the sum of its roads, Dijkstra’s answers against a slow but sure method on 100100 small random graphs, and the rule that closing a road can never make a route faster.

"""Milestone 5: the planner's tests, run with unittest."""
import random
import unittest

from graph import Graph, from_database, travel_seconds
from planner import RoutePlanner, dijkstra


class PlannerTests(unittest.TestCase):
    def setUp(self):
        self.planner = RoutePlanner()

    def test_travel_time(self):
        self.assertEqual(travel_seconds(1000, 36), 100)    # 36 km/h is 10 m/s
        self.assertEqual(travel_seconds(1210, 50), 87)

    def test_one_way_road(self):
        g = from_database(self.planner.conn)
        self.assertEqual(g.arc_count(), 105)
        self.assertEqual(g.one_way_arcs(), [(1, 3)])

    def test_unknown_place(self):
        with self.assertRaises(ValueError):
            self.planner.route("Station", "Libary")

    def test_cost_is_sum(self):
        path, seconds = self.planner.route("Old Mill", "Post Office")
        self.assertEqual(self.planner.cost_of(path), seconds)
Listing 35.11. The tests, first part: travel time, one-way road, unknown place, cost of a route. code/grade-12/14-project-route-planner/listings/planner_tests.py

The slow method starts from the source at cost 00 and, nn times over, tries every arc out of every vertex reached, keeping any improvement. A shortest route has at most n−1n - 1 arcs, so nn rounds are enough to find it. It is much slower than Dijkstra’s algorithm, and too simple to be wrong.

    def test_dijkstra_vs_slow_method(self):
        rng = random.Random(4)
        for _ in range(100):
            g, n = Graph(), rng.randint(2, 7)
            for u in range(n):
                g.add_vertex(u)
                for v in rng.sample(range(n), rng.randint(0, n - 1)):
                    if v != u:
                        g.add_arc(u, v, rng.randint(1, 9))
            best = {0: 0}                        # slow but sure: n rounds
            for _ in range(n):
                for u in list(best):
                    for v, c in g.successors(u):
                        if v not in best or best[u] + c < best[v]:
                            best[v] = best[u] + c
            self.assertEqual(dijkstra(g, 0)[0], best)

    def test_closing_never_helps(self):
        before = self.planner.route("Station", "Library")[1]
        for road in range(1, 54):
            self.planner.close_road(road)
            try:
                after = self.planner.route("Station", "Library")[1]
                self.assertGreaterEqual(after, before)
            except ValueError:
                pass                             # the town split: no route at all
            self.planner.reopen_road(road)


if __name__ == "__main__":
    unittest.main(verbosity=2)
Listing 35.12. The tests, second part: against the slow method, and closed roads. code/grade-12/14-project-route-planner/listings/planner_tests.py
$ bash run_tests.sh
test_closing_never_helps (__main__.PlannerTests.test_closing_never_helps) ... ok
test_cost_is_sum (__main__.PlannerTests.test_cost_is_sum) ... ok
test_dijkstra_vs_slow_method (__main__.PlannerTests.test_dijkstra_vs_slow_method) ... ok
test_one_way_road (__main__.PlannerTests.test_one_way_road) ... ok
test_travel_time (__main__.PlannerTests.test_travel_time) ... ok
test_unknown_place (__main__.PlannerTests.test_unknown_place) ... ok

----------------------------------------------------------------------

OK
Output 35.6. All six pass; the line that gives the duration is left out.

The chapter’s own folder runs the same comparison on the town itself, for every one of the 3030 starting places. The measure runs Dijkstra’s algorithm once from each place, keeps the 870870 ordered pairs, and closes two roads of the Station–Library route one at a time.

"""Milestone 5: every pair of places, the slowest one, and a road closed."""
from graph import from_database
from planner import RoutePlanner, dijkstra, rebuild

planner = RoutePlanner()
g = from_database(planner.conn)
times = {}
for a in g.arcs:                                 # one Dijkstra per starting place
    dist, _ = dijkstra(g, a)
    times.update({(a, b): t for b, t in dist.items() if b != a})
print(len(times), "ordered pairs; mean", round(sum(times.values()) / len(times)), "s")
a, b = max(times, key=times.get)
path = rebuild(dijkstra(g, a)[1], b)
print(f"slowest: {planner.names[a]} to {planner.names[b]}, {times[a, b]} s,"
      f" {len(path) - 1} roads")
names = [planner.names[p] for p in path]
print("  " + " > ".join(names[:6]) + " >")
print("  " + " > ".join(names[6:]))

for road in [2, 6]:
    planner.close_road(road)
    path, seconds = planner.route("Station", "Library")
    print(f"road {road} closed: {seconds} s, {len(path) - 1} roads")
    print("  " + " > ".join(path))
    planner.reopen_road(road)
Listing 35.13. Milestone 5: every pair, the slowest one, and two closures. code/grade-12/14-project-route-planner/listings/run_m5.py
$ python run_m5.py
870 ordered pairs; mean 303 s
slowest: Old Mill to Post Office, 675 s, 10 roads
  Old Mill > Cinema > Theatre > Market Hall > Hill Park > Station >
  River Park > Town Hall > Sports Hall > East Gate > Post Office
road 2 closed: 444 s, 7 roads
  Station > River Park > North Bridge > Swimming Pool > North School > Bus Depot > South Bridge > Library
road 6 closed: 394 s, 5 roads
  Station > Town Hall > River Park > North Bridge > Town Square > Library
Output 35.7. The slowest pair takes 1111 minutes 1515 seconds; closing road 22 adds almost three minutes.

A trip across Brenmoor takes 303303 seconds on average, about five minutes. The slowest pair, the Old Mill and the Post Office, is not the pair farthest apart: exercise 35.15 reads the reason off the map. Closing road 22, between the Town Square and North Bridge, forces a detour through the south of the town, 444−276=168444 - 276 = 168 seconds longer; closing road 66 costs 118118 seconds. The planner answers both without any change to its code: only the set of closed roads differs.

Remark 35.1

The real planners on phones and in cars solve the same problem on graphs of many millions of arcs, with live travel times instead of speed limits. They keep the idea and change the scale: a faster structure for picking the minimum, and work done once in advance so that each question explores only a small part of the graph.

35.7 Exercises

Exercise 35.1 ★

The Bakery Corner has a direct road to the South School, 17301730 m at 3030 km/h. It also has a road to the Theatre, 890890 m at 3030 km/h, and the Theatre one to the South School, 15401540 m at 7070 km/h. What does planner.route("Bakery Corner", "South School") return?

Solution

Solution of Exercise 35.1.

Direct: 3.6×1730/30=207.63.6 \times 1730 / 30 = 207.6, so 208208 s. Through the Theatre: 3.6×890/30=106.83.6 \times 890 / 30 = 106.8, so 107107 s, then 3.6×1540/70=79.23.6 \times 1540 / 70 = 79.2, so 7979 s: 186186 s in all. The call returns (['Bakery Corner', 'Theatre', 'South School'], 186): the longer route is faster.

Exercise 35.2 ★

Road 4343, from the Post Office to the Sports Hall, is 18301830 m long with a limit of 3030 km/h. What is its cost in the graph by time?

Solution

Solution of Exercise 35.2.

3.6×1830/30=219.63.6 \times 1830 / 30 = 219.6, rounded to 220220 seconds, more than three and a half minutes for under two kilometres.

Exercise 35.3 ★

Using only the outputs of the chapter, predict what this query returns on the planner’s database: SELECT COUNT(*), MAX(length_m) FROM road WHERE speed_kmh = 30.

Solution

Solution of Exercise 35.3.

(20, 1830). The count is in the output of milestone 1: 2020 roads at 3030 km/h. The longest road of the town, 18301830 m, is at 3030 km/h (the query of the town’s tables), so it is also the longest of those 2020.

Exercise 35.4 ★

A town has 5353 roads, one of them one-way. How many arcs does its graph have? And if kk of the 5353 roads were one-way?

Solution

Solution of Exercise 35.4.

Two arcs for each of the 5252 two-way roads and one for the one-way road: 105105. With kk one-way roads, 2(53−k)+k=106−k2(53 - k) + k = 106 - k.

Exercise 35.5 ★

Write place_id(conn, name), which returns the number of a place by asking the database with a parameterised query, and raises ValueError if there is no such place.

Solution

Solution of Exercise 35.5.

def place_id(conn, name):

row = conn.execute("SELECT place_id FROM place WHERE name = ?",

(name,)).fetchone()

if row is None:

raise ValueError(f"no place called {name!r}")

return row[0]

The name goes in as a parameter, never pasted into the text of the query, against SQL injection. fetchone returns None when no row matches. The file is exercises/rp_ex.py.

Exercise 35.6 ★★

A student’s version of from_database adds two arcs for every road, without looking at one_way. Which check of milestone 2 fails, and what does the planner now answer for the route from the Library to the Town Square?

Solution

Solution of Exercise 35.6.

The graph now has 106106 arcs, and one_way_arcs() returns [] instead of [(1, 3)]: both checks of milestone 2 that concern road 11 fail, as does the test test_one_way_road. The planner answers 9898 seconds from the Library to the Town Square, straight up the one-way road, the wrong way; the right answer is 204204 seconds, through the Garden Centre.

Exercise 35.7 ★★

Add a third criterion, the route with the fewest roads. Which graph does it need, and what does it give from the Old Mill to the Post Office, compared with the fastest route?

Solution

Solution of Exercise 35.7.

A graph with the same arcs, each of cost 11: the cost of a route is then its number of roads. From the Old Mill to the Post Office, 77 roads is the fewest, but six different routes tie at 77 (from 81408140 to 96509650 m), and which one comes out depends on the order in which the scan meets equal costs. The chapter’s dijkstra returns the one through the South School, the Bakery Corner, the Market Hall, Hill Park, the Town Hall and the Sports Hall: 96509650 m and 985985 s, against 1010 roads, 91309130 m and 675675 s for the fastest route. Fewer roads, but more metres and over five minutes slower. Breadth-first search also finds 77 roads, since all costs are equal, though perhaps another of the tied routes; the tests check the route that dijkstra returns and its two costs with cost_of.

Exercise 35.8 ★★

A shuttle line is added from the Old Mill to the Swimming Pool. Its trip takes a quarter of an hour, and the student stores its cost as 0.25. What goes wrong, and how should the cost be stored?

Solution

Solution of Exercise 35.8.

Every other cost is in seconds, so the planner reads 0.25 as a quarter of a second: the shuttle looks almost free, and every route that can use it does, for routes that in truth take fifteen minutes longer. Python adds the numbers without complaint; nothing but the programmer knows the unit. The cost must be in the graph’s unit: 0.25×3600=9000.25 \times 3600 = 900 seconds. Naming the unit in the code, as in length_m or travel_seconds, makes such a mix visible.

Exercise 35.9 ★★

Milestone 5 runs Dijkstra’s algorithm from each of the 3030 places. With the scan of the listing, about how many comparisons does one run make on a graph of nn vertices, and the whole measure? Is it worth building each graph once instead of for every question?

Solution

Solution of Exercise 35.9.

Each run finishes the nn vertices one by one, and each choice scans at most nn tentative costs: at most n2n^2 comparisons, plus one test per arc. For n=30n = 30, about 900900 per run, so about 30×900=27 00030 \times 900 = 27\,000 for the measure, plus 30×10530 \times 105 arc tests. Building a graph reads 3030 places and 5353 roads, a cost of the same order as one run. Building it once would save little here; on a graph of millions of arcs, it would matter.

Exercise 35.10 ★★

Write roads_on_route(conn, ids), the numbers of the roads that a route uses, given its places. Then show, by a test and by an argument, that closing a road not on the fastest route from the Station to the Library never changes the time of that route.

Solution

Solution of Exercise 35.10.

def roads_on_route(conn, ids):

found = []

for a, b in zip(ids, ids[1:]):

(road,) = conn.execute("SELECT road_id FROM road WHERE (from_place,"

" to_place) IN ((?, ?), (?, ?))", (a, b, b, a)).fetchone()

found.append(road)

return found

The route from the Station to the Library uses roads 66, 3030, 22 and 11. The tests close each of the 4949 others in turn: the time stays 276276 s. The argument: closing a road only removes arcs, so no new route appears and the best time cannot drop. And the old fastest route uses none of the removed arcs, so it is still there, with the same cost: the best time cannot rise either.

Exercise 35.11 ★★

What does the menu print for this input, one line per answer: 1, Town Square, Library, 1, Library, Town Square, 4?

Solution

Solution of Exercise 35.11.

After each prompt the menu waits for one line; the run prints

1 min 38 s over 1 road

Town Square > Library

3 min 24 s over 2 roads

Library > Garden Centre > Town Square

each answer after its prompts, and the program ends at 4. The way there is the one-way road, 9898 s; the way back cannot use it.

Exercise 35.12 ★★★

Write route_avoiding(planner, start, end, avoid), the fastest route that does not pass through the place avoid. What does it give from the Station to the Library, avoiding North Bridge?

Solution

Solution of Exercise 35.12.

Build the graph as usual, then remove the place: delete it from the successors of every vertex, and delete its own entry. Dijkstra’s algorithm on what remains gives the answer (route_avoiding in exercises/rp_ex.py). Avoiding North Bridge, the fastest route from the Station to the Library goes round by the east: River Park, the Town Hall, the Sports Hall, the East Gate and the Garden Centre, 572572 s instead of 276276.

Exercise 35.13 ★★★

Prove that route returns a fastest route: the list of places it returns is a route in the graph, its cost is the number returned, and no route is faster.

Solution

Solution of Exercise 35.13.

A route. Each vertex but the source receives a parent uu only while the arc u→vu \to v is being examined, so parent and child are joined by an arc; following parents from bb reaches the source, whose parent is None, since each parent was finished before its child, so the chain never loops. Reversed, the list is a route from aa to bb.

Its cost. When vv gets parent uu, its tentative cost is set to d(u)+c(u,v)d(u) + c(u, v), where d(u)d(u) is final, uu being finished. If vv later gets a better parent, both change together. So at the end d(v)=d(parent)+c(parent,v)d(v) = d(\text{parent}) + c(\text{parent}, v) for each vv on the route, and adding these equalities along the route gives d(b)d(b) = the sum of the costs of its arcs.

The fastest. The costs are times, all ≥0\ge 0, so the theorem of chapter 26 applies: the cost of each finished vertex is its distance from the source, the smallest cost of any route. Hence no route from aa to bb costs less than d(b)d(b), the cost of the route returned.

Exercise 35.14 ★★★

Write within(planner, start, seconds), the sorted names of the places that can be reached from start in at most that many seconds. Which places are within two minutes of the Station? Why is one run of Dijkstra’s algorithm enough, whatever the limit?

Solution

Solution of Exercise 35.14.

def within(planner, start, seconds):

dist, _ = dijkstra(from_database(planner.conn), planner.place_id(start))

return sorted(planner.names[p] for p, t in dist.items()

if 0 < t <= seconds)

Within 120120 s of the Station: Hill Park, Market Hall, North Bridge, River Park and the Town Hall. The Town Hall is reached in 6868 s through River Park, not in 120120 s by its direct road. One run gives the time to every place, so any limit is a filter on its result. (The run could also stop as soon as the next place to finish is beyond the limit, since the places are finished in order of time.)

Exercise 35.15 ★★★

The Old Mill and the Post Office are 4.94.9 km apart in a straight line, and 675675 seconds apart by road; the South School and the Garden Centre, the pair farthest apart, are 5.65.6 km apart and only 523523 seconds. Using the map of milestone 3 and the roads of the Post Office (three, all at 3030 km/h), explain why the first pair is the slowest.

Solution

Solution of Exercise 35.15.

The Old Mill lies in the south-west corner of the map and the Post Office near the north-east edge. The fastest route does not go straight: it climbs north to the Station, where two roads at 7070 km/h meet, then turns east, 91309130 m of road for 4.94.9 km in a straight line. Its end is slow too: all three roads of the Post Office are at 3030 km/h, so its last 680680 m alone take 8282 s. The South School and the Garden Centre are farther apart, but their route keeps to roads at 5050 and 7070 km/h all the way. Time on a road map depends on the roads, not on the distance between the ends.