In: Computer Science
There is a famous puzzle called the Tower of Hanoi. Code the recursive implementation of it with Python.
# Recursive function definition below
# input params: number of disks used, what is the source
(start_point),what is the target where the disk is intended t be
(end_point) and a intermittent to peroform movement(auxilary)
def TowerOfHanoi(num_disks , start_point, end_point,
auxilary):
if num_disks == 1:
print "Move disk 1 from position
",start_point," to position ",end_point
return
# else Move num_disks-1 disks from
source to auxiliary using the target (end_point) as the
auxilary
TowerOfHanoi(num_disks-1, start_point, auxilary,
end_point)
print "Move disk ",num_disks," from position
",start_point," to position ",end_point
#Move the num_disks-1 disks on the auxiliary to the
end_point using the start_point as the auxiliary.
TowerOfHanoi(num_disks-1, auxilary, end_point,
start_point)
# calling function passing inputs
num_disks = int(input('Enter number of disks: '))
# call the function with num_disks,A as source, B as auxiliary and
C as target
TowerOfHanoi(num_disks, 'A','C','B')
Output: