我想解散以下函数的递归,因为某些输入数据导致递归深度过大错误。 Increasing the recursion depth从长远来看不是解决方案。
def foo(x):
for element in x.elements:
element.depth = x.depth + 1
self.foo(element)
List flattening不适用,因为需要保留原始列表结构。
This solution使用生成器,但包含递归。它是发电机这一事实有什么不同吗?
最后是 stack approach .在这里,我不确定这是否 100% 适用,因为要分配的值是相互依赖的。
什么是优雅的(Pythonic)非递归解决方案?
最佳答案
你基本上是在实现一个 DFS在你的数据上。您的数据是图形,其中每个元素都是一个节点,两个元素之间的连接是一条边。
您可以轻松地用堆栈 DFS 替换递归 DFS,方法是迭代元素并压入堆栈,并一直这样做直到堆栈耗尽。
请注意可能有一个 small difference in the ordering of elements ,但这也很容易解决。
DFS 的伪代码为:
def foo(x):
s = new stack
s.push(x)
while not s.empty()
e = s.pop()
for element in e.elements: # or elements[::-1] for reversed order
element.depth = e.depth + 1
s.push(element)
# if data structure is not a tree, add visited set.
关于python - 遍历嵌套列表并为每个没有递归的元素分配一个相互依赖的值(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42987317/