Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Experiment No- 04

AIM: Write a program in Python or Prolog to implement the Tower of


Hanoi problem.

1. Theory:

1.1 Problem Definition:


Tower of Hanoi is a mathematical problem (puzzle) that consists of 3 poles and ‘n’ number of
discs, each disc having different diameters.

The objective or goal of this problem is to transfer all the ‘n’ discs from source pole to the
destination pole in such a way that we get the same arrangement of discs as before. But this
goal must be achieved by sticking to the rules.
Rules and Constraints
The constraints that must be satisfied while solving the problem are –
1. Only one disc can be moved at a time.
2. Only the top-most disc can be removed
3. The larger disc cannot be placed on top of the smaller disc.

1.2 Solution:
The following picture shows the step-wise solution for a tower of Hanoi with 3 poles (source,
intermediate, destination) and 3 discs. The goal is to move all the 3 discs from pole A to pole
C.
As we can see from the above solution, the number of moves needed for 3 discs = 8. So, a
generalized formula for a total number of moves we need is:

Total number of moves = n2 – 1


2. Code:

# Creating a recursive function


def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
# function call itself
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))
tower_of_hanoi(disks - 1, auxiliary, source, target)

disks = int(input('Enter the number of disks: '))


# We are referring source as A, auxiliary as B, and target as C
tower_of_hanoi(disks, 'A', 'B', 'C') # Calling the function

3. Output:

Enter the number of disks: 3


Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.

You might also like