简体   繁体   English

使用两个自调用了解递归 function 的执行流程

[英]Understanding the flow of execution of a recursive function with two self calls

I need help understanding how this function works:我需要帮助了解这个 function 是如何工作的:

import turtle

annie = turtle.Turtle()

def draw(t, length, n):

    if n == 0:
        return
    angle = 50
    t.fd(length*n)
    t.lt(angle)
    draw(t, length, n-1)
    t.rt(2*angle)
    draw(t, length, n-1)
    t.lt(angle)
    t.bk(length*n)

draw(annie, 30, 4)

turtle.mainloop()

This function creates a symmetrical branched graphic with a large Y shaped branch, with two smaller Y shaped branches hanging off the end of each arm of the larger Y shaped branch.这个 function 创建了一个带有大 Y 形分支的对称分支图形,两个较小的 Y 形分支悬挂在较大 Y 形分支的每个 arm 的末端。 The function ends with the "turtle" (the little arrow that leaves a line behind it as it moves across the screen) going backwards four times from the tip of the final smaller branch it draws and finishing where it started at the beginning of the larger branch. function 以“乌龟”(当它在屏幕上移动时留下一条线的小箭头)结束,从它绘制的最后一个较小分支的尖端向后退四次,并在它从较大分支的开头开始的地方结束分支。 So how does n = 4 by the time the function finishes if the self calls before that statement subtract 1 from the value of n?那么,如果在该语句之前的自我调用从 n 的值中减去 1,那么在 function 完成时 n = 4 是如何实现的呢? And does the first self call iterate through the first few lines of the function back to that self call until n = 0, then move through the rest of the function?第一次自调用是否会遍历 function 的前几行,直到 n = 0,然后通过 ZC1C425268E68385D1AB5074C17A9F 的 rest? In which case, what is the value of n for the first instance of the second self call statement?在这种情况下,第二个自调用语句的第一个实例的 n 值是多少? 4? 4? 0? 0? I think I clearly am misunderstanding something and would appreciate any resources to help me know what I'm doing.我想我显然误解了一些东西,并希望有任何资源来帮助我了解我在做什么。

The reason that n is still 4 when the outermost function finishes is that each function has its own copy of n .当最外面的 function 完成时n仍然是 4 的原因是每个 function 都有自己的n副本。 Each function works in its own scope.每个 function 在其自己的 scope 中工作。

The outermost function passes the value of n to the next function.最外面的 function 将n的值传递给下一个 function。 So each subsequent function creates it's own copy and subtracts 1 from the copy, never touching the n in the outermost functions scope.所以每个后续的 function 创建它自己的副本并从副本中减去 1,从不触及最外层函数 scope 中的n

This works different for lists, objects, etc. though.但是,这对于列表、对象等来说是不同的。

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

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