50 XP

61. Tower of Hanoi

Intermediate recursion

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

Inputn = 1
Output[["A", "C"]]
ExplanationOne disk goes straight across.

Example 2

Inputn = 2
Output[["A", "B"], ["A", "C"], ["B", "C"]]
ExplanationSmall disk aside, big across, small on top.

Example 3

Inputn = 0
Output[]
ExplanationNo disks, no moves.

Constraints

  • n is a whole number from 0 to 6.

Submit also runs 3 more tests you can't see.

Practises Recursion (lesson 20).

Code
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