How Does Return Statement With Recursion Calls Hold Intermediate Values In Python?
Was reviewing some python code related to recursion calls and noticed the return statement looked interesting. How does the recursion work when there is no variable assignment in
Solution 1:
The function returns the value to the call higher in the call stack, why do you think it needs a variable, e.g. take a simple recursive call:
def r(n):
if n == 0:
return0return1 + r(n-1)
Then the call stack would look like:
r(3):
return1 + r(2)
r(2):
return1 + r(1)
r(1):
return1 + r(0)
r(0):
return0
So when you unwind the call stack you get:
r(3):
return1 + r(2)
r(2):
return1 + r(1)
r(1):
return1 + 0
--
r(3):
return1 + r(2)
r(2):
return1 + 1
--
r(3):
return1 + 2
--
3
Solution 2:
As explained by AChampion if you want to see the same kind of stack trace for your code in Pycharm do few steps .
In Pycharm select
Then you can see while debugging each step how the call stack is added and once the operation is done how the values are returned
Post a Comment for "How Does Return Statement With Recursion Calls Hold Intermediate Values In Python?"