Course 3.1Lesson 5 of 5
In this project we build a route finder on a small map of towns. The roads are a dictionary of neighbours, and breadth-first search with a queue finds the shortest route as a list of towns, or None when there is no way. From it we get the number of stops, and a second search gives every town that can be reached. An unknown town is refused with a ValueError. We plan the expected routes by hand, build the functions, test the same town, a town that cannot be reached and an unknown town, and extend the finder with road lengths and a path that avoids a closed town.
Try the code and the simulations beside the lesson.
After this lesson you can
A traveller has a small map of towns in the west of India. The roads join some of the towns. The traveller wants to ask:
And the program must be safe: a town that is not on the map is refused, and a town that cannot be reached gives None, not a crash.
The roads (each road goes both ways):
Work out the answers by hand.
| Question | Answer |
|---|---|
| route Thane to Kolhapur | Thane, Mumbai, Pune, Satara, Kolhapur: 4 stops |
| stops from Pune to Pune | 0 |
| stops from Pune to Goa | cannot be reached |
| towns reached from Nashik | Nashik, Pune, Mumbai, Satara, Thane, Kolhapur |
| route to a town not on the map | refused |
Check the first. From Thane the only road is to Mumbai. From Mumbai to Pune. From Pune, Satara is the way to Kolhapur. That is 4 roads: Thane to Mumbai, Mumbai to Pune, Pune to Satara, Satara to Kolhapur.
| Test | Expected |
|---|---|
| start equals goal | the route is just the start, and 0 stops |
| a town with no roads (Goa) | route to it gives None |
| from the town with no roads | reachable gives only that town |
| an unknown town | ValueError |
| two routes of the same length | either is correct, but the answer must be one of them |
| a graph with a loop (Pune, Mumbai, Nashik) | the search must end |
The third row is easy to miss: reachable(roads, "Goa") is {"Goa"}, the start itself. The last row tests the memory: Pune, Mumbai and Nashik are joined in a triangle, and a search that forgets where it has been would never end.
Goa is reached only through Satara and Kolhapur. Remove the road from Satara to Kolhapur, and shortest_path would give None.
Pick one or two, and do them without looking at a solution. Write the expected answers first.
route(graph, start, goal, closed) avoids the towns in a set closed.KeyError.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
reachable here.None).Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
roads have an entry for Goa with an empty list?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.