I'm new to Python, I found the below recursive program being tough to follow. While debugging the program I could find that it goes through recursion and the value of k decrements -1 every time we recurse. At one point k is -1 and the compiler moves to the else part and returns 0.
Finally, the k value turns out to be 1, how does this happen?
def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result
print("\n\nRecursion Example Results")
tri_recursion(6)
And the output:
Recursion Example Results  
1  
3  
6  
10  
15  
21  
                Try tracing the function with a pencil and paper. In this case, the print statement insde the function may be a bit misleading.
Consider this part of the program,
if(k>0):
    result = k+tri_recursion(k-1)
...
From here,
tri_recursion(6) = 6 + tri_recursion(5)
So to get the result for tri_recursion(6) we must get the result of tri_recursion(5) Following this logic, the problem reduces to:
tri_recursion(6) 
 = 6 + tri_recursion(5) 
 = 6 + 5 + tri_recursion(4)
 = 6 + 5 + 4 + tri_recursion(3)
 = 6 + 5 + 4 + 3 + tri_recursion(2)
 = 6 + 5 + 4 + 3 + 2 + tri_recursion(1)
 = 6 + 5 + 4 + 3 + 2 + 1 + tri_recursion(0)
Now notice that 0 is not greater than 0 so the program moves to the body of the else clause:
else:
    result = 0
...
Which means tri_recursion(0) = 0. Therefore:
tri_recursion(6) 
= 6 + 5 + 4 + 3 + 2 + 1 + tri_recursion(0)
= 6 + 5 + 4 + 3 + 2 + 1 + 0
= 21
k is never equal to -1, infact it is impossible.if you debug the code like this
def tri_recursion(k):
    if(k > 0):
        print('\t'*k,'start loop k',k)
        holder = tri_recursion(k - 1)
        result = k + holder
        print('\t'*k,'i am k(', k,')+previous result(', holder,')=',result)
    else:
        result = 0
        print('i reached when k =', k)
    print('\t'*k,'end loop', k)
    return result
print("\n\nRecursion Example Results")
tri_recursion(6)
you will see the output like
Recursion Example Results
                         start loop k 6
                     start loop k 5
                 start loop k 4
             start loop k 3
         start loop k 2
     start loop k 1
i reached when k = 0
 end loop 0
     i am k( 1 )+previous result( 0 )= 1
     end loop 1
         i am k( 2 )+previous result( 1 )= 3
         end loop 2
             i am k( 3 )+previous result( 3 )= 6
             end loop 3
                 i am k( 4 )+previous result( 6 )= 10
                 end loop 4
                     i am k( 5 )+previous result( 10 )= 15
                     end loop 5
                         i am k( 6 )+previous result( 15 )= 21
                         end loop 6
21
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With