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.
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 to place ” 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.
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.
"""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
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}")
$ 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
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;
$ 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)
35.3 Milestone 2: the graph
The roads become arcs. A road of length metres with a speed limit of km/h takes seconds, since km/h is 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
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
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)))
$ 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}
The three successors of the Station show the point of travel times: River Park and Hill Park, at and metres on roads at km/h, are seconds away, while the Town Hall, at metres on a road at km/h, is 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]
Graph, and the route rebuilt from the parents. code/grade-12/14-project-route-planner/listings/planner.pyThe 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)")
$ 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)
From the Allotments to the Sports Hall the direct road is metres at km/h, seconds; through the College it is metres longer, on two roads at km/h, and takes 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: seconds from the Town Square to the Library, seconds back, through the Garden Centre.
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)
RoutePlanner and its five methods. code/grade-12/14-project-route-planner/listings/planner.pyRoutePlanner 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 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()
$ 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
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 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)
The slow method starts from the source at cost and, times over, tries every arc out of every vertex reached, keeping any improvement. A shortest route has at most arcs, so 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)
$ 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
The chapter’s own folder runs the same comparison on the town itself, for every one of the starting places. The measure runs Dijkstra’s algorithm once from each place, keeps the 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)
$ 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
A trip across Brenmoor takes 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 , between the Town Square and North Bridge, forces a detour through the south of the town, seconds longer; closing road costs 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, m at km/h. It also has a road to the Theatre, m at km/h, and the Theatre one to the South School, m at km/h. What does planner.route("Bakery Corner", "South School") return?
Solution
Solution of Exercise 35.1.
Direct: , so s. Through the Theatre: , so s, then , so s: s in all. The call returns (['Bakery Corner', 'Theatre', 'South School'], 186): the longer route is faster.
Exercise 35.2 ★
Road , from the Post Office to the Sports Hall, is m long with a limit of km/h. What is its cost in the graph by time?
Solution
Solution of Exercise 35.2.
, rounded to 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: roads at km/h. The longest road of the town, m, is at km/h (the query of the town’s tables), so it is also the longest of those .
Exercise 35.4 ★
A town has roads, one of them one-way. How many arcs does its graph have? And if of the roads were one-way?
Solution
Solution of Exercise 35.4.
Two arcs for each of the two-way roads and one for the one-way road: . With one-way roads, .
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 arcs, and one_way_arcs() returns [] instead of [(1, 3)]: both checks of milestone 2 that concern road fail, as does the test test_one_way_road. The planner answers seconds from the Library to the Town Square, straight up the one-way road, the wrong way; the right answer is 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 : the cost of a route is then its number of roads. From the Old Mill to the Post Office, roads is the fewest, but six different routes tie at (from to 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: m and s, against roads, m and s for the fastest route. Fewer roads, but more metres and over five minutes slower. Breadth-first search also finds 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: 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 places. With the scan of the listing, about how many comparisons does one run make on a graph of 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 vertices one by one, and each choice scans at most tentative costs: at most comparisons, plus one test per arc. For , about per run, so about for the measure, plus arc tests. Building a graph reads places and 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 , , and . The tests close each of the others in turn: the time stays 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, 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, s instead of .
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 only while the arc is being examined, so parent and child are joined by an arc; following parents from 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 to .
Its cost. When gets parent , its tentative cost is set to , where is final, being finished. If later gets a better parent, both change together. So at the end for each on the route, and adding these equalities along the route gives = the sum of the costs of its arcs.
The fastest. The costs are times, all , 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 to costs less than , 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 s of the Station: Hill Park, Market Hall, North Bridge, River Park and the Town Hall. The Town Hall is reached in s through River Park, not in 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 km apart in a straight line, and seconds apart by road; the South School and the Garden Centre, the pair farthest apart, are km apart and only seconds. Using the map of milestone 3 and the roads of the Post Office (three, all at 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 km/h meet, then turns east, m of road for km in a straight line. Its end is slow too: all three roads of the Post Office are at km/h, so its last m alone take s. The South School and the Garden Centre are farther apart, but their route keeps to roads at and km/h all the way. Time on a road map depends on the roads, not on the distance between the ends.