Search code examples
python-3.xrecursiontowers-of-hanoi

Function called multiple times with different parameters in recursion problem


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)?


Solution

  • 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;

    1. n = 4, else statement is executed, first line of code in else statement is Towers(4 -1,fr,spare,to), a new function execution is added to the recursion tree
    2. n = 3, else statement is executed, first line of code in else statement is Towers(3 -1,fr,spare,to), a new function execution is added to the recursion tree
    3. n = 2, else statement is executed, first line of code in else statement is Towers(2 -1,fr,spare,to), a new function execution is added to the recursion tree
    4. n = 1, if statement is executed, printmove(fr,to) is worked, recursion is break.
    5. All of the previous recursed function executions on the tree are died in the back order(last added to recursion tree -> first died).
    6. Now, the only working function execution is our first call, Towers(4,"P1","P2","P3") for n = 4
    7. Program flow continues with the next line of code, which is Towers(1,fr,to,spare)
    8. It continues to flow in that logic until last recursive function call is died.

    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.