在我正在学习的一个教程中,有一个用不同级别的分支绘制的树的示例代码。我正在尝试编写一个函数,当树的“level”更改为“indicated by N”时,它将显示分支的数量。你知道吗
在下面的代码中,下面两行带注释的代码显示了我要完成的任务。我完全理解当N增加1时,添加到树中的分支数是3的倍数,但我不理解如何利用函数count_num_branches()
在每次递归调用时显示树上的分支数。你知道吗
__author__ = 'Python Tutotial'
from math import cos, sin, radians, pi
import turtle
""" Run with br = 1, 2, 3, 4, and 5 and put together a recursive formula
that can be used to determine the count)num_branches.
"""
def tree(t, n, x, y, a, branchRadius):
global count
count += 1
bendAngle = radians(15)
branchAngle = radians(37)
branchRatio = .65
cx = x + cos(a) * branchRadius
cy = y + sin(a) * branchRadius
t.width(1 * n ** 1.2)
if t.pensize() < .3:
t.color('pink')
else:
t.color('black')
t.goto(x, y)
t.down()
t.goto(cx, cy)
t.up()
if not n:
return None
tree(t, n-1, cx, cy, a + bendAngle - branchAngle, branchRadius * branchRatio)
tree(t, n-1, cx, cy, a + bendAngle + branchAngle, branchRadius * branchRatio)
tree(t, n-1, cx, cy, a + bendAngle, branchRadius * (1 - branchRatio))
# def count_num_branches(br):
def main():
global count
count = 0
N = 1 #Run with N = 1, 2, 3, 4, and 5
t = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(0, 0, 1, 1)
wn.bgcolor('cyan')
wn.title("My Tree N = "+str(N))
#t.speed(0)
turtle.tracer(15)
t.ht()
t.up()
tree(t, N, .5, 0, pi/2, .3)
# wn.title("My Tree N = {0}, Recursive calls: {1:,} count_num_branches = {2:,}".format(N, count, count_num_branches(br)))
wn.exitonclick()
以下是你所描述的,但我仍然不确定它是否符合你的要求。它基本上通过两种不同的方式计算递归/分支:一种是通过计数;一种是通过递归公式:
相关问题 更多 >
编程相关推荐