无法理解这个递归的海龟python cod

2024-10-01 19:17:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次问问题,希望你们能抽出时间回答。在

所以我的目标是用turtle模块编写一个python脚本来编写pythogras树。在

我花了好几天的时间在这上面,我真的没法超过某一点,所以我上网找我帮忙。我发现了一个代码,它可以满足我的需要,但是代码行很少:

import turtle
t = turtle.Pen()




LIMIT  =11
SCALAR = 0.5 * (2 ** 0.5)


def drawTree(size, depth):

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1)

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1)

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)



def drawSquare(sideLength):

    for i in range(4):
        t.forward(sideLength)
        t.left(90)



t.up(); t.goto(-100, -200); t.down()
drawTree(170.0, 0)

所以我理解大部分代码,除了“如果”的第二段和第三段:它们为什么会被执行?如果函数不断重复,它就永远不会正常到达该点! 我肯定我错过了一些很容易的事情,我希望你们都能理解我的问题:)再次感谢!在


Tags: 代码rightsizedef时间leftforwardscalar
2条回答

drawTree函数不会永远调用自己,因此递归调用之后的语句最终会被执行。当depth==LIMIT处的递归调用返回上一个调用,其中depth==LIMIT-1。在

下面是一个稍微修改过的代码版本,其中包含两个print调用,以帮助跟踪执行情况。在

我还做了一些其他的小改动。我简化了SCALAR的计算:0.5 * sqrt(2)==sqrt(0.5),我只在乌龟画正方形时才放下笔。我还添加了一个turtle.mainloop()调用,这样当绘图完成时窗口将保持打开状态。在

from __future__ import print_function
import turtle

LIMIT = 3
SCALAR = 0.5 ** 0.5
INDENT = ' ' * 4

def drawTree(size, depth, branch):
    print(INDENT * depth, branch, depth, 'start')

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1, 'left ')

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1, 'right')

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)

    print(INDENT * depth, branch, depth, 'stop')


def drawSquare(sideLength):
    t.down()
    for i in range(4):
        t.forward(sideLength)
        t.left(90)
    t.up()


t = turtle.Pen()
t.up() 
t.goto(-100, -200)
drawTree(100.0, 0, 'root')

turtle.mainloop()

输出

^{pr2}$

例如,“depth”是10,在第一段中程序名为drawTree(size*SCALAR,10+1)depth“变为11,若为false,程序返回drawTree,其中“depth”为10。然后程序执行下一行,第二段的第一行。在

同样,程序在第二段中调用drawTree(),而“depth”未达到极限,则返回并转到第三段的第一行。在

相关问题 更多 >

    热门问题