【发布时间】:2018-03-01 14:25:04
【问题描述】:
在我正在学习的教程中,有一个示例代码,其中包含使用不同级别的分支绘制的树。我正在尝试编写一个函数,当树的“级别”更改“由 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()
【问题讨论】:
-
绘制的行数与递归调用计数相同。当 N = 1 时,递归呼叫计数为 4,屏幕上有 4 条线路,一个中继线和三个分支。所以可以计算分支数——你想显示什么(例如树外边缘的“叶子”等)
-
这一行在这里:wn.title("我的树 N = {0},递归调用:{1:,} count_num_branches = {2:,}".format(N, count, count_num_branches( br))) 应该使用一个函数 count_num_branches 来显示 N 的当前值、递归调用的计数以及包括主干在内的分支总数。
标签: python recursion turtle-graphics