Tower of Hanoi in Python

Nkugwa Mark William
2 min readFeb 5, 2023

Tower of Hanoi is a classic puzzle where the goal is to move a stack of n discs from the first peg to the last peg, subject to the restriction that you can only move one disc at a time and you cannot place a larger disc on top of a smaller one. Tower of Hanoi can be solved using recursion. Here is an example implementation in Python:

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

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

Explanation:

  1. The tower_of_hanoi function takes the number of discs, n, and the names of the source, auxiliary, and target pegs as input.
  2. The base case of the recursion is when there is only one disk. In this case, the function simply prints the move to be made.
  3. For the recursive case, the function first solves the subproblem of moving n-1 discs from the source to the auxiliary peg using the target as auxiliary.
  4. Then, the function prints the move of the nth disk from the source to the target peg.
  5. Finally, the function solves the subproblem of moving n-1 discs from the auxiliary to the target peg using the source as auxiliary.
  6. The if __name__ == "__main__" block is a special Python construct that only executes the code inside if the script is run directly (not imported as a module).
  7. In the main block, the number of discs n is initialized to 3 and the tower_of_hanoi function is called to solve the puzzle for n discs.

--

--

Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites