I am fairly new to programming and I was just introduced to the concept of recursion. I've been presented with the famous Towers of Hanoi problem. Here is how the guy in the course I'm following has solved it like this:
def printmove(fr,to):
print('move from'+ str(fr)+'to'+str(to))
def Towers(n,fr,to,spare):
if n == 1:
printmove(fr,to)
else:
Towers(n-1,fr,spare,to)
Towers(1,fr,to,spare)
Towers(n-1,spare,to,fr)
Towers(4,"P1","P2","P3")
What I do not understand is (and most probably it's pretty obvious but I just can't wrap my head around it) how does it know when to pass to the second recursive call Towers(1,fr,to,spare)?
how does it know when to pass to the second recursive call Towers(1,fr,to,spare)?
Actually, the execution order between those recursive functions are determined with this control block;
if n == 1:
printmove(fr,to)
As you can see, once the n variable is reached the value 1, else statement is not going to be reached again and that's why that function execution is going to end(recursion is going to break). Once it ends, program flow is going to continue on the next line of code which is Towers(1,fr,to,spare)
. For your specific example, you have passed the integer value of 4 to your function call Towers(4,"P1","P2","P3")
, so I will try to illustrate the execution order of your program to be more clear;
Towers(4 -1,fr,spare,to)
, a new function execution is added to the recursion treeTowers(3 -1,fr,spare,to)
, a new function execution is added to the recursion treeTowers(2 -1,fr,spare,to)
, a new function execution is added to the recursion treeprintmove(fr,to)
is worked, recursion is break.Towers(4,"P1","P2","P3")
for n = 4Towers(1,fr,to,spare)
So, if there were no if-else logic in that code, the recursion Towers(n-1,fr,spare,to)
would never break and start an infinite recursion.