作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想生成从每片叶子到树根的所有路径。我想用生成器来做,以节省内存(树可以很大)。这是我的代码:
def paths(self, acc=[]):
if self.is_leaf():
yield [self.node]+acc
for child in self.children:
child.paths([self.node]+acc)
但它不起作用。为什么?在根调用,它从上到下遍历树,收集“acc”中的节点。 “acc”应该在每片叶子中返回......
如果 self.children 为空,则 is_leaf() 为真。
最佳答案
这段代码只产生作为根的(直接)子节点的叶子。其他的被访问,它们屈服于上层函数,但上层函数对它们没有任何作用。您需要的是将它们从较低的函数生成到较高的函数:
def paths(self, acc=[]):
if self.is_leaf():
yield [self.node]+acc
for child in self.children:
for leaf_path in child.paths([self.node]+acc): # these two
yield leaf_path # lines do that
这应该可以解决问题。
关于Python(产量): all paths from leaves to root in a tree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7134742/
我是一名优秀的程序员,十分优秀!