【问题标题】:Python (yield): all paths from leaves to root in a treePython(产量):树中从叶子到根的所有路径
【发布时间】:2011-10-31 08:59:52
【问题描述】:

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

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() 为真。

【问题讨论】:

    标签: python yield


    【解决方案1】:

    此代码仅生成作为根的(直接)子级的叶子。其他的被访问,它们屈服于上层函数,但上层函数对它们没有任何作用。您需要将它们从较低的功能产生到较高的功能:

    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
    

    这应该可以解决问题。

    【讨论】:

    • 我一直想知道——有没有一个快速的“yield all”命令,或者是你写的最短的for循环?
    • 在 Python 3.3 中会有一个 yield from 语句自动从另一个生成器中生成项目,因此任何带有 yieldfor 循环都可以编写为生成器表达式做成一行。
    【解决方案2】:

    目前for 循环没有yield 任何东西。它应该产生所有由递归调用生成的元素:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-03
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多