Python 35 · Build a shortest-route hint

Python lesson 35 of 50 · Advanced · About 45 minutes

Let Pip ask for the shortest route through a connected moonbase using breadth-first search.

Pip follows a trail of orange lights past deep craters towards a radio tower.

Mission Use a queue and a set of visited rooms to find a route with the fewest moves.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Save the complete checkpoint below as moonbase_35.py in a project folder and run python moonbase_35.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Queue. Start with one room and no directions.. → Expand. Check untouched neighbours in order.. → Return. Give the first route found to the target..
Queue → Expand → Return

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Start a queue of search jobs

from collections import deque loads a queue-friendly collection. deque([(start, ())]) begins with one job. The job is a pair containing the starting room and an empty tuple of moves. Jobs enter at the right through append and leave at the left through popleft.

Remember which rooms you have queued

seen = {start} makes a set containing the start. A set keeps distinct values. The condition neighbour not in seen prevents repeat visits. seen.add(neighbour) marks the room immediately so another route cannot queue it again before its turn.

Carry a route alongside each room

Each time a job is taken, unpack it with room, moves = queue.popleft(). For every new room, (*moves, direction) makes a route tuple one move longer. The queue processes all paths of one length before longer paths. That is breadth-first search, and here each exit counts as one move.

Report three kinds of result

command[5:] slices away the five characters in "hint ". .title() turns beacon into Beacon, a map key. A nonempty tuple becomes directions joined with " then ". () means start and target match. None means the queue ran out before finding the target.

How the pieces fit The map view shows every exit. The route search applies queue order and a seen set to the same exits, then the terminal turns the answer into a hint.

Follow one run, step by step
  1. Ask for hint beacon from Habitat.
    The first job is Habitat with (). Why The search begins at Pip’s current room with zero moves.
  2. Process Habitat.
    The queue holds Workshop with ('east',) and Greenhouse with ('south',). Why The exits are considered in dictionary order.
  3. Process Workshop, then Greenhouse.
    Workshop queues Beacon with ('east', 'south'). Greenhouse leaves that job in place. Why Beacon was marked as seen the instant it was queued.
  4. Take Beacon from the queue.
    Route: east then south Why The target matches, so the helper returns this two-move route without moving Pip.

Predict before you run Both paths from Habitat to Beacon take two moves. Why does this checkpoint suggest east first?

Reveal the explanation

Habitat’s east exit comes before south in WORLD, so Workshop reaches the queue first. Greenhouse would be an equally short choice. The order settles the tie.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills deque, breadth-first search, visited set, route hints.

1. Explore in distance order

Pip could check every possible route to the Beacon, but many routes return to Habitat in a loop. Breadth-first search starts at Habitat, examines all rooms one move away, then all rooms two moves away, and continues in that order. A deque acts like a queue of inspection jobs. It stores pairs of a room name and a tuple of directions taken so far. Pop from the left to process the oldest job and add new jobs at the right. The empty tuple at the start means no moves have been needed yet.

queue = deque([(start, ())])
    seen = {start}

2. Keep only useful new routes

Take the nearest unchecked room from the left side of the queue. If its name matches the destination, return the moves that got you there. Otherwise visit each valid neighbouring room. Add a neighbour only if it has not already been seen. Mark it seen as soon as you add it, so two rooms cannot both send you to the same neighbour repeatedly. Each appended job remembers the current directions and one new direction. Because the queue works in order of distance, the first route discovered to the target has as few moves as possible.

seen.add(neighbour)
                queue.append((neighbour, (*moves, direction)))

3. Explain special results

The empty tuple means Pip is already at the destination. None means that the search examined everything it could reach and found no route. These two values need different messages. The terminal checks whether a typed room name exists before starting the search. Try hint beacon in Habitat, then move east and ask again. More than one shortest route can exist because Workshop and Greenhouse both connect to Beacon. The current order of the exits determines which tied route is returned. The hint describes a possible route but does not move Pip.

moves = route(state.room, target)
Complete Python checkpoint · moonbase_35.py
from dataclasses import dataclass, replace
from collections import deque

WORLD = {
    "Habitat": {"east": "Workshop", "south": "Greenhouse"},
    "Workshop": {"west": "Habitat", "south": "Beacon"},
    "Greenhouse": {"north": "Habitat", "east": "Beacon"},
    "Beacon": {"north": "Workshop", "west": "Greenhouse"},
}
PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
REQUIRED = {"Coil", "Cell"}


@dataclass(frozen=True)
class State:
    room: str = "Habitat"
    parts: tuple = ()
    rescued: bool = False

def step(state, command):
    if state.rescued:
        return state, "Beacon already online."
    if command.startswith("go "):
        direction = command[3:]
        target = WORLD[state.room].get(direction)
        if target is None:
            return state, "No exit that way."
        return replace(state, room=target), f"Arrived at {target}."
    if command == "take":
        part = PART_AT.get(state.room)
        if part is None:
            return state, "There is no part here."
        if part in state.parts:
            return state, "You already have that part."
        return replace(state, parts=(*state.parts, part)), f"Packed {part}."
    if command == "repair":
        if state.room != "Beacon":
            return state, "Repair at the Beacon."
        if not REQUIRED.issubset(state.parts):
            return state, "Find both the Coil and the Cell."
        return replace(state, rescued=True), "Beacon online!"
    return state, "Unknown command."

def render_map(state):
    rooms = []
    for room, exits in WORLD.items():
        current = " [Pip is here]" if room == state.room else ""
        links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
        rooms.append(f"{room}{current}: {links}.")
    return "\n".join(rooms)

def route(start, target):
    queue = deque([(start, ())])
    seen = {start}
    while queue:
        room, moves = queue.popleft()
        if room == target:
            return moves
        for direction, neighbour in WORLD[room].items():
            if neighbour not in seen:
                seen.add(neighbour)
                queue.append((neighbour, (*moves, direction)))
    return None

def describe(state):
    pack = ", ".join(state.parts) or "empty"
    restored = "online" if state.rescued else "offline"
    message = f"{state.room} | pack: {pack} | Beacon: {restored}"
    return message

def normalise(text):
    return " ".join(text.lower().split())

def play():
    state = State()
    history = []
    print('Moonbase Rescue. Type go east, take, repair, status or quit.')
    while True:
        try:
            command = normalise(input("> "))
        except EOFError:
            break
        if command == "quit":
            break
        if command == "status":
            print(describe(state))
            continue
        if command == "map":
            print(render_map(state))
            continue
        if command == "history":
            print("History:", " > ".join(history) or "no moves yet")
            continue
        if command.startswith("hint "):
            target = command[5:].title()
            if target not in WORLD:
                print("Unknown destination.")
            else:
                moves = route(state.room, target)
                print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
            continue
        next_state, message = step(state, command)
        if next_state != state:
            history.append(command)
        state = next_state
        print(message)
    print("Mission ended.")

if __name__ == "__main__":
    play()

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–22
Line 1 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Line 2 from collections import deque
Bring deque into this file from collections. These names can now be used directly.
Lines 4–9 WORLD = { "Habitat": {"east": "Workshop", "south": "Greenhouse"}, "Workshop": {"west": "Habitat", "south": "Beacon"}, "Greenhouse": {"north": "Habitat", "east": "Beacon"}, "Beacon": {"north": "Workshop", "west": "Greenhouse"}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 10 PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in PART_AT. Each colon pairs a key with its value.
Line 11 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 14 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Line 15 class State:
Define State, a class that groups related data or behaviour.
Line 16 room: str = "Habitat"
Describe the expected type of room as str and provide its starting value.
Line 17 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 18 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 20 def step(state, command):
Define step, a reusable piece of the program. Its input names are state, command. The indented body runs when something calls it.
Line 21 if state.rescued:
Run the indented block only if this check is true.
Line 22 return state, "Beacon already online."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 23–35
Line 23 if command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 24 direction = command[3:]
Work out the value on the right, then store it in direction. The slice copies a portion, stopping before the end index if one is given.
Line 25 target = WORLD[state.room].get(direction)
Work out the value on the right, then store it in target. Look up a key. Use the given fallback, or None, if the key is missing.
Line 26 if target is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 27 return state, "No exit that way."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 28 return replace(state, room=target), f"Arrived at {target}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
Line 29 if command == "take":
Run the indented block only if this check is true.
Line 30 part = PART_AT.get(state.room)
Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing.
Line 31 if part is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 32 return state, "There is no part here."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 33 if part in state.parts:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 34 return state, "You already have that part."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 35 return replace(state, parts=(*state.parts, part)), f"Packed {part}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
Lines 36–49
Line 36 if command == "repair":
Run the indented block only if this check is true.
Line 37 if state.room != "Beacon":
Run the indented block only if this check is true.
Line 38 return state, "Repair at the Beacon."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 39 if not REQUIRED.issubset(state.parts):
Run the indented block only if this check is true. The word not reverses which result counts as true. Check whether every item in this set appears in the other collection.
Line 40 return state, "Find both the Coil and the Cell."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 41 return replace(state, rescued=True), "Beacon online!"
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available.
Line 42 return state, "Unknown command."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 44 def render_map(state):
Define render_map, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 45 rooms = []
Work out the value on the right, then store it in rooms.
Line 46 for room, exits in WORLD.items():
Take one item at a time and give it to room, exits, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 47 current = " [Pip is here]" if room == state.room else ""
Work out the value on the right, then store it in current. Choose the first value if the condition is true, otherwise choose the value after else.
Line 48 links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
Work out the value on the right, then store it in links. Put strings together with the text before .join separating them. The expression supplies matching values one at a time to the operation using it. Python fills the braces with values before it uses the text.
Line 49 rooms.append(f"{room}{current}: {links}.")
Add the value to the end without replacing the earlier entries. Python fills the braces with values before it uses the text.
Lines 50–63
Line 50 return "\n".join(rooms)
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them.
Line 52 def route(start, target):
Define route, a reusable piece of the program. Its input names are start, target. The indented body runs when something calls it.
Line 53 queue = deque([(start, ())])
Work out the value on the right, then store it in queue. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
Line 54 seen = {start}
Work out the value on the right, then store it in seen.
Line 55 while queue:
Check queue before each pass. Repeat the indented work while it is true.
Line 56 room, moves = queue.popleft()
Give each returned value to the matching name, from left to right. Remove and return the oldest entry at the front of the queue.
Line 57 if room == target:
Run the indented block only if this check is true.
Line 58 return moves
Leave this function now and hand the result back to the line that called it.
Line 59 for direction, neighbour in WORLD[room].items():
Take one item at a time and give it to direction, neighbour, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 60 if neighbour not in seen:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 61 seen.add(neighbour)
Add the value to the set. A set keeps at most one copy.
Line 62 queue.append((neighbour, (*moves, direction)))
Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Line 63 return None
Leave this function now and hand the result back to the line that called it.
Lines 65–79
Line 65 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 66 pack = ", ".join(state.parts) or "empty"
Work out the value on the right, then store it in pack. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Line 67 restored = "online" if state.rescued else "offline"
Work out the value on the right, then store it in restored. Choose the first value if the condition is true, otherwise choose the value after else.
Line 68 message = f"{state.room} | pack: {pack} | Beacon: {restored}"
Work out the value on the right, then store it in message. Python fills the braces with values before it uses the text.
Line 69 return message
Leave this function now and hand the result back to the line that called it.
Line 71 def normalise(text):
Define normalise, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 72 return " ".join(text.lower().split())
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them. Separate the string into a list of pieces. Return a lowercase copy so capital letters do not change a command.
Line 74 def play():
Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 75 state = State()
Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
Line 76 history = []
Work out the value on the right, then store it in history.
Line 77 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 78 while True:
Repeat the indented work until a break, return or error ends this path.
Line 79 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Lines 80–92
Line 80 command = normalise(input("> "))
Work out the value on the right, then store it in command. Run normalise with the supplied inputs and come back here when it returns. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 81 except EOFError:
Run this part only when the try block raises EOFError.
Line 82 break
Leave the nearest loop immediately and continue after it.
Line 83 if command == "quit":
Run the indented block only if this check is true.
Line 84 break
Leave the nearest loop immediately and continue after it.
Line 85 if command == "status":
Run the indented block only if this check is true.
Line 86 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 87 continue
Skip the rest of this pass and start the next loop check.
Line 88 if command == "map":
Run the indented block only if this check is true.
Line 89 print(render_map(state))
Show the message or value in the output. Run render_map with the supplied inputs and come back here when it returns.
Line 90 continue
Skip the rest of this pass and start the next loop check.
Line 91 if command == "history":
Run the indented block only if this check is true.
Line 92 print("History:", " > ".join(history) or "no moves yet")
Show the message or value in the output. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 93–105
Line 93 continue
Skip the rest of this pass and start the next loop check.
Line 94 if command.startswith("hint "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 95 target = command[5:].title()
Work out the value on the right, then store it in target. Return words with title-style capital letters for display.
Line 96 if target not in WORLD:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 97 print("Unknown destination.")
Show the message or value in the output.
Line 98 else:
Take this branch if the earlier checks for this decision were false.
Line 99 moves = route(state.room, target)
Work out the value on the right, then store it in moves. Run route with the supplied inputs and come back here when it returns.
Line 100 print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Put strings together with the text before .join separating them.
Line 101 continue
Skip the rest of this pass and start the next loop check.
Line 102 next_state, message = step(state, command)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 103 if next_state != state:
Run the indented block only if this check is true.
Line 104 history.append(command)
Add the value to the end without replacing the earlier entries.
Line 105 state = next_state
Work out the value on the right, then store it in state.
Lines 106–110
Line 106 print(message)
Show the message or value in the output.
Line 107 print("Mission ended.")
Show the message or value in the output.
Line 109 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 110 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Draw the current search queue after examining Habitat.
  • Ask for a route to the room Pip is already in.
  • Temporarily remove every path into Beacon, then check that the hint reports unreachable.

If something goes wrong

The same rooms keep appearing.
Add each neighbour to seen when it enters the queue.
The route starts from the wrong place.
Pass state.room as the first argument to route.

Mission extension

Add a valid new room and try hints to and from it. Check the route length using the visible map.