Python Program For Tower Of Hanoi

6 min read

Python Program for Tower of Hanoi: A Complete Guide to Implementing the Classic Recursive Algorithm

Let's talk about the Tower of Hanoi is a timeless puzzle that challenges logical thinking and recursion skills. Whether you are a student learning algorithmic concepts or a developer looking to showcase recursive programming in Python, creating a Python program for Tower of Hanoi provides a clear demonstration of how elegant solutions can emerge from simple rules. This article walks you through the problem’s fundamentals, explains the recursive algorithm, and presents a clean, well‑documented Python implementation. You will also find tips on testing, common variations, and performance considerations to help you adapt the solution to real‑world scenarios Took long enough..

Introduction

About the To —wer of Hanoi consists of three pegs and a set of disks of different sizes stacked on one peg. The objective is to move the entire stack to another peg while obeying two strict rules: only one disk can be moved at a time, and a larger disk can never be placed on top of a smaller one. Which means this puzzle, invented by French mathematician Édouard Lucas in 1883, is often used to teach recursion because its solution naturally breaks down into smaller, self‑similar sub‑problems. A python program for tower of hanoi typically leverages recursion to achieve the minimal number of moves, which is mathematically proven to be (2^n - 1) for n disks.

Understanding the Tower of Hanoi Problem

Before diving into code, it’s essential to grasp the problem’s constraints and the optimal solution’s characteristics.

  • Pegs: Usually labeled as source, auxiliary, and target.
  • Disks: Represented by integers where a smaller integer denotes a smaller disk.
  • Rules:
    1. Only the top disk of any peg can be removed.
    2. A disk can only be placed on an empty peg or on a larger disk.

The puzzle’s optimal solution requires the fewest possible moves, which is (2^n - 1). To give you an idea, with three disks, the minimum moves are (2^3 - 1 = 7). Any algorithm that deviates from this count is either non‑optimal or incorrect.

Recursive Algorithm Explanation

The recursive nature of Tower of Hanoi is its most fascinating aspect. Solving the puzzle for n disks can be reduced to three steps:

  1. Move the top n‑1 disks from the source peg to the auxiliary peg, using the target peg as temporary storage.
  2. Move the largest disk (nth disk) directly from the source peg to the target peg.
  3. Move the n‑1 disks from the auxiliary peg to the target peg, using the source peg as temporary storage.

This approach repeats until the base case is reached: when there is only one disk (n = 1), simply move it from source to target. The recursion ensures that each sub‑problem is solved exactly once, leading to an elegant and efficient solution Practical, not theoretical..

Python Implementation Steps

Below is a step‑by‑step guide to building a python program for tower of hanoi. The implementation focuses on clarity and educational value.

Step 1: Define the Function Signature

def tower_of_hanoi(n, source, auxiliary, target):
  • n: Number of disks.
  • source, auxiliary, target: Peg identifiers (commonly strings like 'A', 'B', 'C').

Step 2: Base Case Handling

If n == 1, the function prints the move directly:

if n == 1:
    print(f"Move disk 1 from {source} to {target}")
    return

Step 3: Recursive Calls

The function calls itself three times to accomplish the three steps described earlier:

tower_of_hanoi(n - 1, source, target, auxiliary)   # Step 1
print(f"Move disk {n} from {source} to {target}") # Step 2
tower_of_hanoi(n - 1, auxiliary, source, target)   # Step 3

Step 4: Driver Code

To execute the algorithm, we need a driver that sets up the number of disks and initiates the recursion:

if __name__ == "__main__":
    disks = int(input("Enter the number of disks: "))
    tower_of_hanoi(disks, 'A', 'B', 'C')

Complete Code

Combining all steps yields the full program:

def tower_of_hanoi(n, source, auxiliary, target):
    if n == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    tower_of_hanoi(n - 1, source, target, auxiliary)
    print(f"Move disk {n} from {source} to {target}")
    tower_of_hanoi(n - 1, auxiliary, source, target)

if __name__ == "__main__":
    disks = int(input("Enter the number of disks: "))
    tower_of_hanoi(disks, 'A', 'B', 'C')

Code Walkthrough

  • Function Definition: The tower_of_hanoi function is generic; it works for any number of disks and any peg naming scheme.
  • Base Case: When n == 1, the recursion stops, and a single move is printed.
  • Recursive Calls: The first call moves n‑1 disks from source to auxiliary, the second moves the largest disk, and the third moves the remaining n‑1 disks from auxiliary to target.
  • Driver: The if __name__ == "__main__": block ensures the script can be run directly or imported without unintended side effects.

Testing and Running the Program

  1. Save the code in a file named tower_of_hanoi.py.

  2. Run the script using a Python interpreter:

    python tower_of_hanoi.py
    
  3. Provide input when prompted. Here's one way to look at it: entering 3 should produce the following 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
    

    Verify that the moves follow the puzzle’s rules and that exactly seven moves are printed for three disks Simple, but easy to overlook. Worth knowing..

Common Variations and Extensions

While the classic version is sufficient for learning recursion, you may encounter variations that expand the puzzle’s complexity:

  • Iterative Solution: An iterative approach uses a stack to simulate recursion, which can be useful for understanding how recursion is implemented under the hood.
  • Visual Representation: Adding ASCII art or using libraries like matplotlib to animate disk movements can make the program more engaging.
  • Multiple Towers: Extending the problem to four or more pegs (the Reve’s puzzle) introduces more complex algorithmic strategies.
  • Performance Metrics: Counting the number of moves or measuring execution time can help compare recursive versus iterative implementations.

Performance Considerations

The recursive solution is optimal in terms of move count, but it does incur function call overhead. For very large n (e.That said, g. , > 20), Python’s recursion limit may be reached, causing a RecursionError Surprisingly effective..

To handle larger inputs, you can raise the recursion limit using sys.setrecursionlimit(), though this should be done with caution—excessive recursion depth risks crashing the interpreter or consuming too much memory.

import sys
sys.setrecursionlimit(10000)

Time and Space Complexity

The algorithm makes exactly (2^n - 1) moves, giving it a time complexity of (O(2^n)). This exponential growth means that even modest increases in disk count dramatically increase runtime: 20 disks require over one million moves, and 30 disks exceed one billion Easy to understand, harder to ignore. Which is the point..

The space complexity is (O(n)) due to the recursion stack. Each recursive call adds a frame until the base case is reached, so the maximum depth equals the number of disks Practical, not theoretical..

When to Avoid Recursion

For production systems or puzzles with hundreds of disks, the recursive approach becomes impractical. In such cases, consider:

  • Iterative algorithms using explicit stacks or bitwise operations
  • Tail-call optimization (though Python does not natively support this)
  • Mathematical closed-form solutions that calculate move sequences without simulation

Final Thoughts

The Tower of Hanoi remains one of the most elegant introductions to recursion. In practice, its minimal code belies deep mathematical properties—binary representations, Gray codes, and the Sierpiński triangle all emerge from its structure. While Python’s recursion limits and exponential time complexity constrain its scalability, the puzzle serves as an enduring benchmark for understanding divide-and-conquer thinking, algorithm analysis, and the art of breaking complex problems into manageable subproblems.

Fresh from the Desk

Fresh Content

Parallel Topics

Explore a Little More

Thank you for reading about Python Program For Tower Of Hanoi. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home