gpt4 book ai didi

python - 递归函数帮助/解释

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:22 24 4
gpt4 key购买 nike

有人能解释下 lower 大于 upper 并返回 0 后会发生什么吗?我无法理解程序是如何生成 4,7,9,10 的。我相信 0 是从 ourSum() 函数中调用 ourSum() 的迭代返回的。这会将结果设置为 1 + 0,即等于 1。有人可以花点时间来指导我完成这个过程吗?

def ourSum(lower, upper, margin=0):
blanks = ' ' * margin
print(blanks, lower, upper)
if lower > upper:
print(blanks, 0)
return 0
else:
results = lower + ourSum(lower + 1, upper, margin + 4)
print(blanks, results)
return results

ourSum(1,4) 的结果如下:

 1 4
2 4
3 4
4 4
5 4
0
4
7
9
10
10

最佳答案

这是对正在发生的事情的粗略说明:让我们暂时忘记 printmargin

  • 首先我们有 ourSum(1,4)
    • else 子句发生:它返回 1 + ourSum(2,4)
      • 另一个elseourSum(2,4) 返回2 + ourSum(3,4)
        • ourSum(3,4) 返回 3 + ourSum(4,4)
          • ourSum(4,4) 返回 4+ourSum(5,4)
            • 最后是ifreturn ourSum(5,4) 返回 0。
          • 所以 ourSum(4,4) 返回 4+0 = 4
        • 现在 ourSum(3,4)3+4 = 7
      • 好的,ourSum(2,4)2+7 = 9
    • ourSum(1,4) 返回 1+9 = 10

printmargin 用于很好地报告这些情况。

关于python - 递归函数帮助/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29326633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com