Skip to content

Tower of Hanoi in Python

Seven lines of Python solve the puzzle for any number of disks. Watch them run beside the board, then take them apart.

On this page
  1. The recursive solution, running
  2. Run it yourself
  3. Line by line
  4. Python’s recursion limit
  5. Counting the moves
  6. Without recursion
  7. Keeping the moves instead of printing them
  8. The same algorithm in other languages
  9. Frequently asked questions

The recursive solution, running

Step through the program. The lit line is the one executing, the towers are labelled for the call that is running, and the stack lists every call still waiting to finish.

hanoi(3, "A", "C", "B")

Move 3 disks from A to C.

Nothing is running yet. The first step makes this call.

Step 0 of 43

Call stack

Depth 0 of 4 max

  1. Empty. Nothing has been called yet.

hanoi.py

def hanoi(n, source, target, spare):
    """Move n disks from source to target, using spare as working space."""
    if n == 0:
        return
    hanoi(n - 1, source, spare, target)
    print(f"Move disk {n} from {source} to {target}")
    hanoi(n - 1, spare, target, source)


if __name__ == "__main__":
    hanoi(3, "A", "C", "B")

Moves

7 in all

Choose a row to jump the program to that move.

Every move the program makes for 3 disks
MoveDiskFromTo
11AC
22AB
31CB
43AC
51BA
62BC
71AC

Run it yourself

Save the listing as hanoi.py and run it:

Run it

python hanoi.py

It prints the seven moves of the three-disk puzzle:

Output

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Change the 3 in the call to solve a bigger puzzle. Every disk you add doubles the output, plus one line.

Line by line

Not what each line says — the listing says that — but why it has to be there:

LineWhy it is there
1The three towers are parameters rather than fixed names because every call has to disagree with its parent about which tower is which — that disagreement is the algorithm. n is both how many disks to move and the number of the largest one, which is what lets line 6 print it.
2The one thing the signature cannot tell you is which of the three names is the destination and which is the scratch space. That is what the docstring is for; nothing else in the function needs a comment.
3–4Recursion needs a size it can answer without calling itself, or it never stops. Zero disks is that size: nothing to move, so nothing to do. Python checks no types on the way in, so only a whole number counts down onto it — hanoi(2.5, …) steps straight past zero and ends in RecursionError. Stopping at n == 1 would halve the calls, but the move would then have to be written twice.
5Disk n is going to target, so target has to be clear when it arrives — which is exactly why the n - 1 disks on top of it cannot be sent there. They go to spare instead, and that is why the last two arguments trade places: this call's spare is that call's target.
6The only line in the program that moves a disk. It is legal here and nowhere else, because line 5 has just cleared everything smaller than n off both the source and the target.
7The mirror of line 5. The n - 1 disks are sitting on spare now, so spare is the source this time, and the original source — which holds nothing smaller than n any more — is free to be the working space.
10–11Guards the call so that importing this file from another program does not print seven lines as a side effect of loading it. The argument order is the function's, not the puzzle's: A is the source, C the target, and B is whatever is left over.

Why those three lines are enough — the correctness proof, the recurrence and the complexity — is on the Tower of Hanoi algorithm page, and holds for every language here.

Python’s recursion limit

Python refuses to recurse past a fixed depth — 1,000 frames by default in CPython, which sys.getrecursionlimit() reports — and raises RecursionError instead. For plenty of recursive functions that is a real constraint. For this one it never is.

The recursion only ever goes n + 1 calls deep, because each call finishes before its sibling starts: count the rows in the call stack above, and three disks never need more than four. So the limit would come into play at around a thousand disks, and a thousand-disk puzzle takes 2¹⁰⁰⁰ − 1 moves — a number with 302 digits. The program would never get far enough through its output to reach the stack’s edge.

Counting the moves

count_moves.py

def minimum_moves(n):
    """2**n - 1, exactly. Python integers grow as large as they need to."""
    return 2**n - 1


for n in (3, 10, 64):
    print(f"{n} disks: {minimum_moves(n)} moves")

Run it

python count_moves.py

Output

3 disks: 7 moves
10 disks: 1023 moves
64 disks: 18446744073709551615 moves

Python integers have no fixed width. 2**64 - 1 is exactly 18,446,744,073,709,551,615 with no special type, no import and no overflow, and 2**1000 - 1 would be exact too. That is unusual among the languages here: in Java the obvious expressions quietly give 0, and in JavaScript they quietly round.

Without recursion

hanoi_iterative.py

def hanoi_iterative(n):
    pegs = {"A": list(range(n, 0, -1)), "B": [], "C": []}
    # Disk 1 always travels the same way round: A, C, B for an odd n, A, B, C for an even n.
    cycle = "ACB" if n % 2 == 1 else "ABC"

    for move in range(1, 2**n):
        smallest_at = cycle[(move // 2) % 3]
        if move % 2 == 1:
            # Odd moves: disk 1 steps on to the next tower in its cycle.
            source, target = smallest_at, cycle[(move // 2 + 1) % 3]
        else:
            # Even moves: the one legal move that leaves disk 1 alone.
            a, b = (peg for peg in "ABC" if peg != smallest_at)
            if not pegs[a] or (pegs[b] and pegs[b][-1] < pegs[a][-1]):
                source, target = b, a
            else:
                source, target = a, b
        disk = pegs[source].pop()
        pegs[target].append(disk)
        print(f"Move disk {disk} from {source} to {target}")


if __name__ == "__main__":
    hanoi_iterative(3)

Run it

python hanoi_iterative.py

This version keeps the towers as three lists, largest disk first, and makes one pass of the loop per move. Two rules choose every move.

On odd-numbered moves, the smallest disk steps on to the next tower of its circuit: "ACB" for an odd number of disks, "ABC" for an even number. Disk 1 has made move // 2 moves before this one, so cycle[(move // 2) % 3] is always the tower it is standing on, and the next letter along is where it goes.

On even-numbered moves, the two towers that do not hold disk 1 allow exactly one legal move between them — a smaller top disk onto a larger one, or onto an empty tower — and the if works out which way round it goes by comparing their top disks.

It prints the same seven lines as the recursive program, and at every size the same moves in the same order. The iterative solution explains why two such plain rules reproduce the recursion exactly.

Keeping the moves instead of printing them

To work with the moves rather than print them, give the function a list as a fifth argument, replace the print with moves.append((n, source, target)), and pass the list along in both recursive calls. Nothing else changes.

Bear in mind what you are collecting. The list holds 2ⁿ − 1 tuples: about a million at twenty disks — roughly 75 MB in CPython — and a billion at thirty, roughly 75 GB, more memory than most machines have. If you only need the moves one at a time, yield them instead of storing them, as the JavaScript generator does.

The same algorithm in other languages

Frequently asked questions

How do you solve Tower of Hanoi in Python?

With a recursive function: if n is 0, return; otherwise call hanoi(n - 1, source, spare, target), print the move of disk n from source to target, and call hanoi(n - 1, spare, target, source). Calling hanoi(3, "A", "C", "B") prints the seven moves of the three-disk puzzle.

Will Python hit its recursion limit on Tower of Hanoi?

Not for any puzzle you could wait for. The recursion is only n + 1 calls deep, and CPython's default limit is 1,000, so it would only matter at around a thousand disks — a puzzle of 2¹⁰⁰⁰ − 1 moves, a number with 302 digits.

How do I solve Tower of Hanoi in Python without recursion?

Keep the three towers as lists and loop 2ⁿ − 1 times. On odd-numbered moves, move the smallest disk one step round a fixed circuit — A, C, B for an odd number of disks, A, B, C for an even number. On even-numbered moves, make the only legal move that does not touch the smallest disk. The result is exactly the same sequence of moves as the recursive version.