gpt4 book ai didi

Python Turtle 递归树

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:20 25 4
gpt4 key购买 nike

我想用 python 的 turtle 编写一个程序来创建一个有层次的树。下面是一些 I/O,以便您了解它应该做什么。

enter image description here

我的程序适用于第一种情况,但对于第二种情况打印太多。该程序的规定是:

  • 必须是递归的

  • 只能使用以下 turtle 函数:

    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

我的程序:

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

最佳答案

我认为有两个问题。

首先,对于递归调用,第二个参数应该是 n-1 而不是 length/n。如果您正在绘制第 n 层,则下一次调用将绘制第 n-1 层,而不是第 n 层。

第二个问题是转义条件。对于第一个更改,绘图将在没有更多级别可供绘制时完成,或者 n==1。

这听起来像是作业,所以我不会发布确切的代码。

关于Python Turtle 递归树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12809304/

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