Recursive generator

Paul Hankin paul.hankin at gmail.com
Tue Feb 12 06:39:24 EST 2008


On Feb 12, 11:15 am, Ben C <spams... at spam.eggs> wrote:
> Suppose I have an object containing an array called children. I can
> therefore build a tree out of such objects.
> The best I came up with so far is :
>
>     def genDescendents(self):
>         for child in self.children:
>             yield child
>             for grandChild in child.genDescendents():
>                 yield grandChild

Looks fine, although I'd include self in the generator because I think
that's more logical, (and spell descendant correctly :).

def genDescendants(self):
    yield self
    for child in self.children:
        for grandchild in child.genDescendants():
            yield grandchild


Often generators can be written more concisely with itertools at the
expense of some readability, and that's true here.

from itertools import chain

def genDescendants(self):
    return chain([self], *[child.genDescendants()
        for child in self.children])

--
Paul Hankin




More information about the Python-list mailing list