【发布时间】:2018-12-04 13:30:08
【问题描述】:
这些示例来自 Mark Lutz 的 Learning Python。第一个函数是一个递归函数,用于遍历具有任意嵌套的列表以计算元素的总和:
def sumtree_rec(L):
tot = 0
for x in L:
if not isinstance(x, list):
tot += x
else:
tot += sumtree(x)
return tot
第二个函数实现了同样的功能,但没有递归:
def sumtree_notrec(L):
tot = 0
items = list(L)
while items:
front = items.pop(0)
if not isinstance(front, list):
tot += front
else:
items.extend(front)
return tot
我相信我了解这两个功能的工作原理。我追踪了 sumtree_notrec 中的 L 如何随着代码体的每次迭代而变化,并且它与书中的输出相匹配。我也想我理解为什么递归被认为是一个堆栈,因为每个级别都会将一个调用帧推送到运行时堆栈,并在调用完成时弹出。
我不明白为什么递归函数被称为先进先出队列?我查了一下,感觉我明白数据结构代表什么,只是不明白它们如何应用于这个函数。我还发现了这个资源,它对调用堆栈做了一些解释:https://www.cs.ucsb.edu/~pconrad/cs8/topics.beta/theStack/02/
例如,如果我在非递归函数中跟踪 L(不是实际代码,只是一个表示):
L --> [1,[2,[3,4],5],6,[7,8]]
L --> (1) is popped [[2,[3,4],5],6,[7,8]]
L --> [2,[3,4],5] is not popped
L --> [6,[7,8],2,[3,4],5]
等等……
为什么这叫队列?什么对象是“先入”然后是“先出”?
【问题讨论】:
标签: python-3.x data-structures