【问题标题】:Recursively drawing squares in Python在 Python 中递归绘制正方形
【发布时间】:2017-02-05 21:30:34
【问题描述】:
我无法递归绘制正方形。我的问题是当我递归调用它时应该将什么长度传递给我的 draw_squares 函数。我似乎无法让它正确地适合原始正方形。查找附加的输出示例。 Output example
draw_squares(side_size, depth):
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
if depth > 1:
turtle.penup()
turtle.left(90)
turtle.forward(side_size * 1 / 2)
turtle.right(90)
turtle.pendown()
else:
pass
#Draw diagonal squares within original square
def draw_squares2(side_size, depth):
if depth > 1 and depth % 2 == 0:
turtle.right(45)
draw_squares(side_size * 1/3, depth - 1)
【问题讨论】:
标签:
python
recursion
turtle-graphics
【解决方案1】:
首先,您在此处递归地绘制正方形:draw_squares2 仅调用draw_squares,它从不调用自身或其父级。递归函数直接或间接调用自身。看起来您正在努力实现递归解决方案(将海龟移动到一侧的中间),但您还没有到达那里。
除其他事项外,我注意到您链接到您的帖子的图片似乎与上面的代码不匹配。还是……
正如其他人所指出的,您遇到的问题是基本几何:以 45 度角与另一个正方形内接的正方形的边长是多少?您需要的长度是父正方形边长的 sqrt(2) / 2 倍。
跟踪您如何使用此值;您的程序容易乘以 2 或除以 2。考虑在关键点使用 print 语句来跟踪您的计算。
【解决方案2】:
提出的问题不是递归的,但它可能是递归的。我在下面使用 stamping 编写了一个示例方法,虽然不能直接转换为您的 drawing 方法,但应该给您一些想法,但不是解决方案:
from turtle import Turtle, Screen
colors = ["navy", "gold"]
STAMP_UNIT = 20
def draw_figure(turtle, side_size, depth):
turtle.turtlesize(side_size / STAMP_UNIT)
turtle.color(colors[depth % 2], "white")
turtle.stamp()
if depth < 1:
return
turtle.forward(side_size / 4)
turtle.left(45)
draw_figure(turtle, side_size / 2 / 2**0.5, depth - 1)
turtle.right(45)
turtle.backward(side_size / 2)
turtle.left(45)
draw_figure(turtle, side_size / 2 / 2**0.5, depth - 1)
turtle.right(45)
turtle.forward(side_size / 4) # return to starting point
yertle = Turtle(shape="square", visible=False)
yertle.penup()
draw_figure(yertle, 240, 3)
screen = Screen()
screen.exitonclick()
在深度 3 我们得到:
但是将深度设置为 1 会使我们得到有问题的原始数字: