How does return statement with recursion calls hold intermediate values in Python?

喜你入骨 提交于 2019-12-30 11:21:34

问题


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 the return statement for the next recursive call?

As the recursive calls were being made, the intermediate summed values weren't getting stored in an obvious place. The debugger seems to show the list reducing by one each call, but I just don't understand where the intermediate values are getting stored.

Another interesting thing is the debugger seems to iterate one final time through the values once the final call has been made. Using PyCharm, but not sure if that matters.

How does the return statement hold the summed values during the recursive calls in following recursions?

def sum_list(list_of_num):
    if len(list_of_num) == 1:
        return list_of_num[0]
    else:
        return list_of_num[0] + sum_list(list_of_num[1:])

print(sum_list([4,6,7,3,7,3,2]))

回答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:
         return 0
    return 1 + r(n-1)

Then the call stack would look like:

r(3):
    return 1 + r(2)
    r(2):
        return 1 + r(1)
        r(1):
            return 1 + r(0)
            r(0):
                return 0

So when you unwind the call stack you get:

r(3):
    return 1 + r(2)
    r(2):
        return 1 + r(1)
        r(1):
            return 1 + 0
--
r(3):
    return 1 + r(2)
    r(2):
        return 1 + 1
--
r(3):
    return 1 + 2
--
3



回答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



来源:https://stackoverflow.com/questions/45766736/how-does-return-statement-with-recursion-calls-hold-intermediate-values-in-pytho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!