Professional Documents
Culture Documents
AIM
OBJECTIVE
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.
PROCEDURE
1.Create function hanoi that takes the number of disks n and the names of the source,
auxiliary and target pegs as arguments.
2. The base case is when the number of disks is 1, in which case simply move the
one disk from source to target and return.
3. Move n – 1 disks from source peg to auxiliary peg using the target peg as the
auxiliary.
4. Move the one remaining disk on the source to the target.
5. Move the n – 1 disks on the auxiliary peg to the target peg using the source peg
as the auxiliary.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with
name, source, destination and aux (only to help moving the disks). If we have only one disk,
then it can easily be moved from source to destination peg.
If we have 2 disks −
1
Our ultimate aim is to move disk n from source to destination and then put all
other (n1) disks onto it. We can imagine to apply the same in a recursive way for
all given set of disks.
PROGRAM
Here is the source code of a Python program to implement Tower of Hanoi. The program
output is shown below.
def hanoi(disks, source, auxiliary, target):
if disks == 1:
print('Move disk 1 from peg {} to peg {}.'.format(source, target))
return
hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from peg {} to peg {}.'.format(disks, source, target))
hanoi(disks - 1, auxiliary, source, target)
2
disks = int(input('Enter number of disks: '))
hanoi(disks, 'A', 'B', 'C'
Program Explanation
1. The user is prompted for the number of disks n.
2. The function hanoi is called on n with names of the source, auxiliary and target pegs as
A, B and C respectively.
OUTPUT
3
RESULT
Thus the python program for towers Hanoi is excecuted and output is obtained
successfully.