Python Program for the Tower of Hanoi
Intermediate · Recursion
The Tower of Hanoi is a puzzle with three rods and a stack of disks of different sizes on the first rod, smallest on top. The goal is to move the whole stack to another rod, one disk at a time, without ever putting a bigger disk on a smaller one. With 3 disks it takes 7 moves, and recursion gives a short solution for any number of disks.
Program
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 Total moves: 7 The formula 2^n - 1 gives: 7
How it works
- The rods are called A, B and C, all the disks start on A, and
hanoi()movesndisks fromsourcetotargetusingspareas the extra rod. - The base case is a single disk, which can always go straight to the target in 1 move.
- For more disks, the recursive step moves the top
n - 1disks to the spare rod, moves the biggest disk to the target, then moves then - 1disks from the spare rod onto it. - Moving
n - 1disks is the same puzzle with one disk fewer, which is why the function can call itself to do it. - The function returns how many moves it made, 7 for 3 disks, which matches the formula 2^n - 1, so every extra disk doubles the work.
Other ways to write it
Showing the rods after each move
Start: {'A': [3, 2, 1], 'B': [], 'C': []}
Disk 1: A -> C {'A': [3, 2], 'B': [], 'C': [1]}
Disk 2: A -> B {'A': [3], 'B': [2], 'C': [1]}
Disk 1: C -> B {'A': [3], 'B': [2, 1], 'C': []}
Disk 3: A -> C {'A': [], 'B': [2, 1], 'C': [3]}
Disk 1: B -> A {'A': [1], 'B': [2], 'C': [3]}
Disk 2: B -> C {'A': [1], 'B': [], 'C': [3, 2]}
Disk 1: A -> C {'A': [], 'B': [], 'C': [3, 2, 1]}
End: {'A': [], 'B': [], 'C': [3, 2, 1]}Each rod is a list used as a stack, so pop() takes its top disk and append() puts it on another rod, and printing the rods after every move shows that a bigger disk never lands on a smaller one; this version uses 0 disks as its base case.
Moves needed for more disks
Disks Moves 1 1 2 3 3 7 4 15 5 31 10 1,023 20 1,048,575 64 18,446,744,073,709,551,615
The move count follows the same recursion as the puzzle, and the legend of monks moving 64 golden disks would need 18,446,744,073,709,551,615 moves.
Try it yourself
Change disks to 4 and check that the program makes 15 moves.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises