Question
Write a Python program using Python 3.6.2. The program should be saved as a text file with the extention '.py'. Tower of Hanoi problem is
Write a Python program using Python 3.6.2. The program should be saved as a text file with the extention '.py'.
Tower of Hanoi problem is stated as follows: There are 3 pegs 1, 2 and 3 and initially we have a stack of different sized disks in peg 1 with a smaller disk on top of a larger disk. The task is to move these disks to peg 2 using the other peg if necessary with the restriction that you can only move a disk from top of the stack and place it on a larger disk in another peg. For example, if we have 2 disks in peg 1, we can do the following: (a) Move top disk from peg 1 to peg 3, (b) Move the bottom disk from peg 1 to peg 2, (c) Move the disk from peg3 to peg 2. Can you extend this to 3 disks? Think recursively and that approach should work for any n.
Write a recursive function tower_of_hanoi(n, fromPeg, toPeg) that prints the disc moves required to move a stack of n disks from fromPeg to toPeg where fromPeg and toPeg are integers between 1 and 3. Test your function for n=3 and n=4. For example, the call tower_of_hanoi(3,1,2) should print the following:
Move disk from peg 1 to peg 2
Move disk from peg 1 to peg 3
Move disk from peg 2 to peg 3
Move disk from peg 1 to peg 2
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started