In this tutorial we learn about The Tower of Hanoi problem solving in python is a classic problem in computer science and mathematics. It involves three rods and a number of disks of different sizes which can be slid onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, with the smallest disk on top. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
- Only one disk can be moved at a time.
- Each move consists of taking the top disk from one of the stacks and placing it on top of another stack.
- No disk may be placed on top of a smaller disk.
def tower_of_hanoi(n, source, target, auxiliary): if n == 1: print(f"Move disk 1 from rod {source} to rod {target}") return tower_of_hanoi(n-1, source, auxiliary, target) print(f"Move disk {n} from rod {source} to rod {target}") tower_of_hanoi(n-1, auxiliary, target, source)
Example :
-
num_disks = 3 tower_of_hanoi(num_disks, 'A', 'C', 'B')
num_disks = 3 tower_of_hanoi(num_disks, 'A', 'C', 'B')
In this code
n
is the number of disks.source
,target
, andauxiliary
are the names of the three rods.- The
tower_of_hanoi
function is a recursive function that solves the Tower of Hanoi problem. - It prints the sequence of moves needed to solve the problem.
- When you run this code with
num_disks = 3
, it will print the sequence of moves required to move all the disks from rod ‘A’ to rod ‘C’. You can change the value ofnum_disks
to solve the problem for different numbers of disks.