Monday 30 December 2019

Tower Of Hanoi


Tower of Hanoi
def toh(n,p1,p2,p3): #n= no of disks, p1=source pole,p2=intermediate, pole,                                     #p3=target pole
    if n>0: # at least one disk is required
        toh(n-1,p1,p3,p2) #move pole1 to pole 2, p3 is acting as intermediate pole
        print("move a disk from pole %i pole %i"%(p1,p3))
        toh(n-1,p2,p1,p3) #move n-1 disk from pole 2 to pole 3,pole1 acting as                #intermediate pole
n=int(input("enter no of disks "))
toh(n,1,2,3)# function call
       
"""output:
>>> toh(2,1,2,3)
enter no of disks 2
move a disk from pole 1 pole 2
move a disk from pole 1 pole 3
move a disk from pole 2 pole 3
>>>
>>> """ 

Related video link: https://youtu.be/Pkhmy6eFM0Y
Prev Recursive Function
Next:Lambda function

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...