递归-为什么这段代码打印数字序列不起作用



我很抱歉在这里问这样一个琐碎的初学者问题,但是每次我在理解递归上向前走两步,我似乎就会后退三步。我不明白为什么这个简单的代码在数组中存储n个数字会产生空白。我可以通过执行注释部分来让它工作,但是在顶部的部分中,它不起作用,我假设当堆栈帧展开时y和x将被填充,并且数组应该返回一个数字列表。有人可以解释什么是错误的我的假设和如何可视化递归,以及如何使用的结果,而调用递归地,当返回值传播回主函数?

def nums(n,x):
if n == 0:
return n
else:
y=(nums(n-1,x))
x.append(y)    
return x                # output was all blanks
#  nums(n-1,x)
#  x.append(n)
return x                  # This works
x=[]       
print(nums(7,x))

我们通常教递归的方法是用不同的值进行堆栈跟踪来演示流程。

nums(0, []) => 0 # n.b., this is a scalar, not an array based on the code above
nums(1, []) =>
y = (nums(0, x)) => 0 (from above) # n.b., this might be interpreted as a tuple since we have surrounded it with parentheses, best to avoid enclosing parentheses if you don't need them
x.append(y) => x = [ 0 ]
return x => [ 0 ]

现在我们变得棘手了,因为x是list,所以它是通过引用传递的并返回。对于n>1,我们将把x附加到自身,这将导致问题

nums(2, []) =>
y = nums(1, []) =>
y = nums(0, []) =>
y = 0
x = [ 0 ]
=> [ 0 ]
x.append(x = [ 0 ]) => yields a circular reference since we are appending x to itself

你可能打算使用堆栈展开语义,但如果这是我们的意图,我们需要新的列表作为局部变量,因为我们做递归:


def nums(n):
if n == 0:
return [ 0 ]
return [ n ] + nums(n - 1)

最新更新