def printMove(source, destination):
print('move From ' + str(source) + ' to destination ' + str(destination))
count +=1
print count
def Towers(n, source, destination, spare):
if not count in locals():
count = 0
if n == 1:
printMove(source, destination)
count +=1
else:
Towers(n-1, source, spare, destination)
Towers(1, source, destination, spare)
Towers(n-1, spare, destination, source)
I wrote this script to solve the "Towers of Hanoi". The script works wonderfully, but I also want to print the number of moves it took to solve the problem. I just cannot figure out how I can put a counter kind of thing which will count:
- The number of moves it will take to solve.
- The number of times the "Towers" function was executed.
The if not count in locals(): condition is one of the failed attempts to count the number of moves it will take to solve. Am I on the right track anyway?
Also, is this algorithm efficient? Or is there a better way to solve this?
Moreover, can someone tell me some useful application of Towers of Hanoi and the advantage of recursion? The only one that I could figure out was its simplicity.