Python Program to Implement Tower of Hanoi

Python Program to Implement Tower of Hanoi

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

Source Code:

#Follow - @Programmerfect

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




Comments