Python(yield):树中从叶子到根的所有路径

发布于 2024-11-30 14:44:57 字数 347 浏览 1 评论 0原文

我想生成树中从每片叶子到根的所有路径。我想用生成器来做到这一点,以节省内存(树可能很大)。这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可爱暴击 2024-12-07 14:44:57

此代码仅生成作为根的(直接)子代的叶子。其他的被访问,它们屈服于上层函数,但上层函数对它们不做任何事情。你需要的是将它们从较低的函数产生到较高的函数:

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

这​​应该可以解决问题。

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:

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

This should do the trick.

颜漓半夏 2024-12-07 14:44:57

目前,for 循环不会产生任何结果。相反,它应该生成由递归调用生成的所有元素:

for child in self.children:
    for path in child.paths([self.node]+acc):
        yield path

At the moment the for loop doesn't yield anything. It should instead yield all the elements that are generated by the recursive call:

for child in self.children:
    for path in child.paths([self.node]+acc):
        yield path
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文