61. Tower of Hanoi
Three pegs stand in a row: A, B and C. On peg A sits a tower of n disks, each smaller than the one below it. The
puzzle is to move the whole tower to peg C:
- move one disk at a time, taking the top disk of one peg and putting it on top of another;
- never put a disk on a smaller one.
Write a function hanoi(n) that takes the number of disks and returns the moves of the shortest solution, in order.
Each move is a list [from_peg, to_peg], such as ["A", "C"]. The shortest solution takes 2^n - 1 moves, and there
is only one, so the list is the same for everyone. With no disks there is nothing to move: [].
Example 1
n = 1[["A", "C"]]Example 2
n = 2[["A", "B"], ["A", "C"], ["B", "C"]]Example 3
n = 0[]Constraints
nis a whole number from 0 to 6.
Submit also runs 3 more tests you can't see.
Practises Recursion (lesson 20).
- Think about the biggest disk. Before it can move from A to C, the n - 1 disks on top of it must all be on B, out of the way.
- So: move n - 1 disks from A to B (using C as the spare), move the biggest disk from A to C, then move the n - 1 disks from B to C (using A as the spare).
- Moving n - 1 disks is the same puzzle, so write a helper
move_tower(n, start, spare, end, moves)that calls itself, and stop atn == 0. Note how the pegs swap roles in the two calls.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def hanoi(n):
"""List the moves that carry n disks from A to C.
n: int, the number of disks, 0 or more
Returns: list of [from_peg, to_peg] pairs, the shortest
solution in order
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.