Problem Statement:
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.
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod.
The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
1 2 3 4 5 6 7 8 9 10 11 12 | 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') |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.