Users Online

· Guests Online: 122

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Tower of Hanoi Program in Python

Tower of Hanoi Program in Python

 

 

This is a Python program to implement Tower of Hanoi.

Problem Description

The program prompts the user for the number of disks n and the program prints the procedure to move n disks from peg A to peg C using peg B.

Problem Solution

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.

Program/Source Code

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)
 
 
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.

Runtime Test Cases
Case 1:
Enter number of disks: 4
Move disk 1 from peg A to peg B.
Move disk 2 from peg A to peg C.
Move disk 1 from peg B to peg C.
Move disk 3 from peg A to peg B.
Move disk 1 from peg C to peg A.
Move disk 2 from peg C to peg B.
Move disk 1 from peg A to peg B.
Move disk 4 from peg A to peg C.
Move disk 1 from peg B to peg C.
Move disk 2 from peg B to peg A.
Move disk 1 from peg C to peg A.
Move disk 3 from peg B to peg C.
Move disk 1 from peg A to peg B.
Move disk 2 from peg A to peg C.
Move disk 1 from peg B to peg C.
 
Case 2:
Enter number of disks: 2
Move disk 1 from peg A to peg B.
Move disk 2 from peg A to peg C.
Move disk 1 from peg B to peg C.
 
Case 3:
Enter number of disks: 1
Move disk 1 from peg A to peg C.

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.93 seconds
10,261,505 unique visits