Python海龟递归树
我想用python的turtle编写一个程序,创建一个具有级别的树。下面是一些I/O,您可以看到它应该做什么 我的程序对第一种情况有效,但对第二种情况打印太多。该计划的规定如下:Python海龟递归树,python,tree,turtle-graphics,Python,Tree,Turtle Graphics,我想用python的turtle编写一个程序,创建一个具有级别的树。下面是一些I/O,您可以看到它应该做什么 我的程序对第一种情况有效,但对第二种情况打印太多。该计划的规定如下: 必须是递归的 只能使用以下功能: turtle.forward(100) <-- turtle goes forward 100 steps turtle.right(90) <-- turtle turns right 90 degrees turtle.penup()
- 必须是递归的
- 只能使用以下功能:
turtle.forward(100) <-- turtle goes forward 100 steps turtle.right(90) <-- turtle turns right 90 degrees turtle.penup() <-- turtle lifts its pen up off of the paper turtle.forward(100) <-- turtle goes forward 100 steps turtle.pendown() <-- turtle puts its pen down on the paper turtle.pencolor("red") <-- turtle uses red pen turtle.circle(100) <-- turtle draws circle of radius 100 turtle.pencolor("blue") <-- turtle changes to blue pen (most other common colors work too!) turtle.forward(50) <-- turtle moves forward 50 steps turtle.xcor() <-- turtle returns its current x-coordinate turtle.ycor() <-- turtle returns its current y-coordinate
turtle.forward(100)我认为有两个问题 首先,对于递归调用,第二个参数应该是n-1,而不是length/n。如果您正在绘制标高n,下一次调用将绘制标高n-1,而不是标高长度/n 第二个问题是逃逸条件。在第一次更改中,当没有更多标高可供绘制时,或n==1时,绘制将完成
这听起来像是家庭作业,所以我不会发布确切的代码。我不知道turtle是内置在python中的。你绝对让我开心。import turtle def tree(length,n): """ paints a branch of a tree with 2 smaller branches, like an Y""" if length < (length/n): return # escape the function turtle.forward(length) # paint the thik branch of the tree turtle.left(45) # rotate left for smaller "fork" branch tree(length * 0.5,length/n) # create a smaller branch with 1/2 the lenght of the parent branch turtle.right(90) # rotoate right for smaller "fork" branch tree(length * 0.5,length/n) # create second smaller branch turtle.left(45) # rotate back to original heading turtle.backward(length) # move back to original position return # leave the function, continue with calling program