Question

Write a Python program that implements the Towers of Hanoi, using the recursive algorithm discussed in...

Write a Python program that implements the Towers of Hanoi, using the recursive algorithm discussed in class.

Use command-line arguments to pass parameters to the program -

spring% python towersOfHanoi.py
USAGE: towersOfHanoi.py <# rings> <FROM peg> <TO peg>
spring% python towersOfHanoi.py  4 1 3
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
Move disk from peg 3 to peg 1
Move disk from peg 3 to peg 2
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 2 to peg 1
Move disk from peg 3 to peg 1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code is as follows:

import sys #import sys for command line arguments

def TowerOfHanoi(n , from_peg, to_peg, aux_peg): #TowerOfHanoi function with n as no of disks from_peg(source),to_peg(destination),aux_peg(auxiliary)
if n == 1:
print("Move disk from peg",from_peg,"to peg",to_peg)
return
TowerOfHanoi(n-1, from_peg, aux_peg, to_peg) #recusrsive call to TowerOfHanoi
print("Move disk","from peg",from_peg,"to peg",to_peg)
TowerOfHanoi(n-1, aux_peg, to_peg, from_peg) #recusrsive call to TowerOfHanoi

pegs = [1,2,3] #pegs are 1,2 and 3
n = int(sys.argv[1]) #get n from command line argv 1
from_peg = int(sys.argv[2]) #get source from argv 2
to_peg = int(sys.argv[3]) #get destination from argv 3

pegs.remove(from_peg) #remove from_peg from pegs
pegs.remove(to_peg) #remove to_peg from pegs
aux_peg = pegs[0] #then take the remaiing peg as auxiliary peg
  

TowerOfHanoi(n,str(from_peg),str(to_peg),str(aux_peg)) #function call

************************************************************************************************************************************

Screesnhot of the code:

Output:

Add a comment
Know the answer?
Add Answer to:
Write a Python program that implements the Towers of Hanoi, using the recursive algorithm discussed in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT