Categories
python starter projects

Super Simple Python: Tower of Hanoi

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering the Tower of Hanoi puzzle game in 10 lines of Python!

We’ve covered many different types of games in the Super Simple Python series so far including the High Low Guessing Game, Rock Paper Scissors, and Hangman. This is the first game that we’re covering that has a recursive solution. The recursive solution is not the only solution, just the simplest.

Tower of Hanoi – 3 disks

The rules of the game are simple:

  1. Only 1 disk may be moved at a time
  2. Each move consists of taking the top disk from one stack and placing it onto another
  3. No disk may be placed on top of a disk that is smaller than it

In this post, we will cover:

  • The Recursive Tower of Hanoi Solution in Python
    • Tower of Hanoi with 3 Disks Python Solution

Recursive Tower of Hanoi Solution

To build a recursive solution to the Tower of Hanoi, we will build a function that takes four parameters. The parameters we’ll need are the number of disks, and representations of the start, middle, and end rods. If there’s only 1 disk, we’ll simply move that disk from the start rod to the end rod and return. Otherwise, we’ll run the recursive function on the set of disks minus 1 on two setups. First we’ll move a disk from the start to the middle rod, then from the middle to the end rod. 

Why can we simply run this function recursively on the Tower of Hanoi puzzle but with one less disk? Solving the puzzle for n disks is the same as solving it for n-1 disks. This recursive solution allows us to apply that n-1 logic by moving the n-1 disks from the start to the middle and then the middle to the end.

def tower_of_hanoi(disks, start, middle, end):
    if disks == 1:
        print(f"Move disk 1 from {start} to {end}")
        return
    tower_of_hanoi(disks-1, start, end, middle)
    print(f"Move disk {disks} from {start} to {end}")
    tower_of_hanoi(disks-1, middle, start, end)

Showing the Tower of Hanoi Solution for Three Disks

Okay, now that we’ve created our recursive solution to the Tower of Hanoi, let’s take a look at it. For this example, we’ll take a three disk puzzle and take a look at the solution. We’ll label our rods as A, B, and C.

number_of_disks = 3
tower_of_hanoi(number_of_disks, 'A', 'B', 'C')

When we run our program, it will show us a solution like the one below. This is the same as the solution shown in the gif above.

Tower of Hanoi – 3 Disk Solution Representation

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.