【发布时间】:2016-10-11 18:00:04
【问题描述】:
我正在学习 Think Python,我已经达到了递归,这让我很难理解。
There's this exercise,第 5 号,向我展示了这段代码:
def draw(t, length, n):
if n == 0:
return
angle = 50 #sets angle
fd(t, length*n) #make a turtle() "t" go forward length*n pixels while drawing
lt(t, angle) #makes turtle "t" turn left on itself "angle" (50) degrees
draw(t, length, n-1) #1st call
rt(t, 2*angle) #makes turtle "t" turn right "2*angle" (100) degrees
draw(t, length, n-1) #2nd call
lt(t, angle) #makes turtle "t" turn left "angle" (50) degrees
bk(t, length*n) #makes turtle "t" go backwards length*n pixels
并要求我考虑它的作用,然后运行它。我运行了它,但我无法理解它为什么会这样做。 这是一个更复杂的递归案例,书籍用于解释这个设备,我无法理解。 为了理解这个问题的一个简单实例,让我们将 n 设为示例 2: 我可以弄清楚的是,代码在 n=0 之前连续调用自己直到第一次调用,然后将控件返回到 n=1 并使剩余的代码行从调用 1 到调用 2。它使用第二次调用n=0 并返回,但我无法理解它返回程序控制的函数实例。 如果有人能指出我正确的方向,我会很高兴如何自己思考这种递归代码,我如何利用它(当 for 语句不能完全实现时)以及一种模式化的方法它的工作方式(例如,使用某种图表?)。 我有这个:
function called with n=2
function called with n=1
function called with n=0; returns to:
function called with n=1 makes the 2nd call to the function with n=0
function called with n=0; returns to where?
??????
如您所见,这对于 n = 7 的函数调用是非常不切实际的。
【问题讨论】:
标签: python algorithm recursion