简体   繁体   English

了解递归函数python

[英]understanding recursive function python

I am trying to understand what happens when this recursive function is called. 我试图了解调用此递归函数时会发生什么。 The code is supposed to be a trace 该代码应该是跟踪

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

if __name__ == "__main__":
    mysum(1, 4, 0)

the output reads 输出显示

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

I don't understand why the function begins to unwind after it returns 0. Can you help me follow through what happens 我不明白为什么函数在返回0后就开始展开。您能帮我跟踪发生的情况吗

In brief, you always make a recursive call before you reach a return statement, until you reach the base case. 简而言之,您总是在到达return语句之前进行递归调用,直到达到基本情况为止。 Then, you always reach a return statement before you reach another recursive call (trivially so, since there is only one recursive call). 然后,您总是会在到达另一个递归调用之前就到达return语句(这很简单,因为只有一个递归调用)。

When one call of the function returns 0 ("bottoms out"), there might be many other calls to the function on the stack, waiting to proceed. 当该函数的一次调用返回0(“自下而上”)时,堆栈上可能还有许多其他对该函数的调用,等待继续。 When the recursion bottoms out, control returns to the last-but-one function on the stack. 当递归达到最低点时,控制权将返回到堆栈上的最后一个函数。 It finishes its work and returns, and control returns to the next earlier function on the stack. 它完成工作并返回,然后控制返回到堆栈上的下一个较早的函数。 This continues until all the calls to mysum have been removed from the stack, in reverse order to the order on which they were put on the stack. 这将继续进行,直到所有对mysum的调用都从堆栈中删除为止(与将它们放在堆栈中的顺序相反)。

Maybe you understood all that already :) If so, please clarify what you mean by "why the function begins to unwind." 也许您已经了解了所有内容:)如果是这样,请说明“为什么函数开始展开”的含义。

I think a useful observation here is that the first five lines are printed before any of the nested calls returns. 我认为这里有用的观察是,在任何嵌套调用返回之前先打印前五行。 This all happens in the first part of the function body: 这一切都发生在函数主体的第一部分:

print - check condition - go to else - and go to beginning again, one level deeper. print -检查条件-转到else -并从头再下一层。

When 0 is printed, the deepest call returns, so the second-deepest result gets calculated. 打印0 ,将返回最深的调用,因此将计算出第二个最深的result Then the print from the next line occurs - and it's the first line with 3 numbers in it. 然后从下一行开始print -这是第一行,其中有3个数字。 Then you hit another return , so another result is calculated, etc. The consecutive returns correspond to earlier calls - thus they have less blanks . 然后,您点击另一个return ,从而计算出另一个result ,依此类推。连续收益对应于较早的调用-因此它们的blanks更少。

Here is the code with comments helping you to begin to understand how the recursive function works. 这是带有注释的代码,可帮助您开始理解递归函数的工作方式。

def mysum(lower, upper, margin):
    blanks = ' ' * margin     # First time : margin = 0
                              # 2nd time : margin = 4
    print blanks, lower, upper   # first time : lower = 1, upper = 4
                                 # 2nd time : lower = 2, upper = 4
    if lower > upper:   # first time : go to else (& 2nd time, ... until lower =5)
        print blanks, 0
        return 0
    else:
        result = lower + mysum(lower + 1, upper, margin + 4)   # result is not directly calulated
                                                               # first it need to execute the call to
                                                               # the function, it will be the second call
        print blanks, result, lower, margin
        return result

if __name__ == "__main__":
    mysum(1, 4, 0)     # First call of your function

When lower is at 5, there is no call to mysum and it returns 0. So you unwind just one step : lower is at 4, and you where in the "else" part. 当lower为5时,不会调用mysum,它返回0。因此,您只需要展开一个步骤:lower为4时,您将位于“ else”部分。 You have to finish it 你必须完成它

result = lower + mysum(lower + 1, upper, margin + 4)
print blanks, result, lower, margin
return result

with lower = 4 and the last call returned 0. The result = 4. And you unwind another step : lower is at 3, and the call just before returned a 4, so the new result is 7. This value is returned. 与lower = 4,最后一次调用返回0。结果=4。然后展开另一步骤:lower在3处,而调用恰好在返回4之前,因此新结果为7。返回此值。

Now, lower = 3, you do the same, for lower = 2, lower = 1. 现在,lower = 3,对lower = 2,lower = 1,您也可以这样做。

You can see that 1 + 2 + 3 + 4 = 10. And it is the result of your function. 您会看到1 + 2 + 3 + 4 =10。这是函数的结果。 I hope that I helped you, tell me if you don't understand, maybe can I find another way to explain ... :/ 我希望我能帮助您,告诉我您是否不理解,也许我能找到另一种方式来解释...:/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM