带有递归调用的 return 语句如何在 Python 中保存中间值? [英] How does return statement with recursion calls hold intermediate values in Python?

查看:81
本文介绍了带有递归调用的 return 语句如何在 Python 中保存中间值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在查看一些与递归调用相关的 Python 代码,并注意到 return 语句看起来很有趣.当下一次递归调用的 return 语句中没有变量赋值时,递归如何工作?

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.

另一件有趣的事情是调试器似乎会在进行最后一次调用后对这些值进行最后一次迭代.使用 PyCharm,但不确定这是否重要.

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.

return 语句如何在后续递归中的递归调用期间保存求和值?

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

推荐答案

该函数将值返回给调用堆栈中更高层的调用,为什么您认为它需要一个变量,例如进行一个简单的递归调用:

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

这篇关于带有递归调用的 return 语句如何在 Python 中保存中间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆