I was studying tower of hanoi recursive implementation in python. In my prgram I gave print at different points to know it better like
def hanoi(n, src, inm, dest):
print "n=",n,"src=",src,"inm=",inm,"dest=",dest
if n == 0:
return
hanoi(n-1, src, dest, inm)
print src, '->', dest
print n
hanoi(n-1, inm, src, dest)
hanoi(2,'A','B','C')
The answer is printed like:
n= 2 src= A inm= B dest= C
n= 1 src= A inm= C dest= B
n= 0 src= A inm= B dest= C
A -> B
1
n= 0 src= C inm= A dest= B
A -> C
2
n= 1 src= B inm= A dest= C
n= 0 src= B inm= C dest= A
B -> C
1
n= 0 src= A inm= B dest= C
I could understand upto
1
n= 0 src= C inm= A dest= B
I couldnt understand how A -> C is printed after this. After the call with n= 0 src= A inm= B dest= C, I know function will be returned. There the active function is n= 1 src= A inm= C dest= B. What happens to that?
Please explain the trace
If you add two more prints:
Then you will see that there were two returns in a row: