Python(yield):树中从叶子到根的所有路径
我想生成树中从每片叶子到根的所有路径。我想用生成器来做到这一点,以节省内存(树可能很大)。这是我的代码:
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() 为 true。
I want to generate all paths from every leaf to root in a tree. I'd like to do that with generators, to save memory (tree can be big). Here's my code:
def paths(self, acc=[]):
if self.is_leaf():
yield [self.node]+acc
for child in self.children:
child.paths([self.node]+acc)
But it doesn't work. Why? Invoked at root, it traverses the tree from top to bottom, collecting nodes in "acc". "acc" should be returned in every leaf...
is_leaf() is true if self.children is empty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码仅生成作为根的(直接)子代的叶子。其他的被访问,它们屈服于上层函数,但上层函数对它们不做任何事情。你需要的是将它们从较低的函数产生到较高的函数:
这应该可以解决问题。
This code only yields leaves that are (immediate) children of the root. The other ones get visited, they yield to the upper function, but the upper function does nothing with them. What you need is to yield them from the lower function to the upper one:
This should do the trick.
目前,
for
循环不会产生任何结果。相反,它应该生成由递归调用生成的所有元素:At the moment the
for
loop doesn'tyield
anything. It should instead yield all the elements that are generated by the recursive call: