gpt4 book ai didi

python - 在 Python 中绘制分形树

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

我正在尝试用 Python 绘制一棵分形树,它有 3 个分支。我知道如何画一棵有 2 个 Twig 的树,但有 3 个 Twig ……不确定试图找到例子,但找不到。只找到有两个 Twig 的树的例子。有没有人知道如何做到这一点?

对于 2 分支树,我使用了以下代码:

import turtle
def tree(f_lenght, min_lenght=10):
"""
Draws a tree with 2 branches using recursion
"""
turtle.forward(f_lenght)
if f_lenght > min_lenght:
turtle.left(45)
tree(0.6*f_lenght, min_lenght)
turtle.right(90)
tree(0.6*f_lenght, min_lenght)
turtle.left(45)
turtle.back(f_lenght)

turtle.left(90)
tree(100)
turtle.exitonclick()

最佳答案

这是一个扩展的例子。使用您的方法制作分支,很容易让它们重叠,所以我添加了一些参数来帮助实现这一点。请随意使用代码,但这是任意递归级别的示例。

import turtle
def tree(f_length, spray=90., branches=2, f_scale=0.5, f_scale_friction=1.4, min_length=10):
"""
Draws a tree with 2 branches using recursion
"""
step = float(spray / (branches - 1))
f_scale /= f_scale_friction
turtle.forward(f_length)
if f_length > min_length:
turtle.left(spray / 2)
tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
for counter in range(branches - 1):
turtle.right(step)
tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
turtle.left(spray / 2)
turtle.back(f_length)

turtle.left(90)
tree(80, spray=120, branches=4)
turtle.exitonclick()

关于python - 在 Python 中绘制分形树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392646/

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