Search This Blog

Tower of Hanoi in Python




# define function as t_hanoi
# no = number of plates
# start = start pole
# tmp = Temporary pole
# goal = Goal pole

def t_hanoi(no, start, tmp, goal):
    if no <= 1:
        print("Move disk %s from %s  -------> %s" % (no, start, goal))
    else:
        t_hanoi(no - 1, start, goal, tmp)
        print("Move disk %s from %s -------> %s " % (no, start, goal))
        t_hanoi(no - 1, tmp, start, goal)

print(t_hanoi(3, 'Start Pole', 'Temp Pole', 'Goal Pole'))

“””
Output:

Move disk 1 from Start Pole  -------> Goal Pole
Move disk 2 from Start Pole -------> Temp Pole
Move disk 1 from Goal Pole  -------> Temp Pole
Move disk 3 from Start Pole -------> Goal Pole
Move disk 1 from Temp Pole  -------> Start Pole
Move disk 2 from Temp Pole -------> Goal Pole
Move disk 1 from Start Pole  -------> Goal Pole

“””



Post a Comment

0 Comments