天哪!多么有趣的问题:)
由于您自称是“循环者”,所以我会像循环一样考虑递归。
在for 循环中,执行循环体直到满足for 循环条件。现在,递归非常相似。您一直调用该函数,直到函数的参数不再遇到递归情况。他们遇到了一个基本情况,然后返回一个递归可以建立的值。
所以这么想递归,我们来想想怎么画一个正方形。您需要首先确定代码的哪些部分被重复(即尝试执行相同操作的 for 循环的主体中的内容)。然后,确定您希望何时停止此重复(即我如何知道 for 循环何时退出)。
在绘制正方形时,我可以想到至少重复 4 次的两个主要事物。乌龟前进一定的步数,乌龟转 90 度(或 270 度,取决于方向)。所以这将是我们在递归案例中详述的内容。
现在,让我们考虑一下基本情况。好吧,我们知道正方形有 4 条边,所以在乌龟画完 4 条边后,我们希望它停止。
最后,让我们考虑一下函数声明以及递归情况和基本情况这两个部分如何发挥作用。函数声明可以采用以下形式(在 Python 中):
def draw_square_recursive(turn_deg=90, side_len, sides=4):
"""
Function draws a square with turtle graphics recursively
:param turn_deg: an int, the number of degrees a turtle should turn
:param side_len: an int, the length of a side of the square
:param sides: an int, the number of sides in our square
"""
turn_deg 和side_len 对于我们的递归案例很重要,因为它们定义了乌龟应该如何转动以及它应该“走”多远。 sides 是一个有趣的参数,我们可以使用它来决定是继续重复还是停止。如果我们每次画边时都从sides 中减去1,我们就会知道我们需要在sides == 0 时停止重复,这是一个基本情况!
因此,每当我们再次调用我们的函数时,我们都会将其称为draw_square_recursive(side_len, sides-1):
总的来说,函数的结构如下:
def draw_square_recursive(turn_deg=90, side_len, sides=4):
"""
Function draws a square with turtle graphics recursively
:param turn_deg: an int, the number of degrees a turtle should turn
:param side_len: an int, the length of a side of the square
:param sides: an int, the number of sides in our square
"""
if sides == 0:
# base case!
else:
# recursive case!
请注意,这个函数名为draw_square_recursive,但它可以更泛化到其他形状。你知道怎么做吗?
对不起,如果这是一个冗长的答案!希望对你有帮助;p