Recursive generator

Ben C spamspam at spam.eggs
Tue Feb 12 13:34:34 CET 2008

On 2008-02-12, Paul Hankin <paul.hankin at> wrote:
> 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 :).

I actually prefer descendent. It may be more American English since it's
closer to Latin. "Descendant" is basically French. But anyway, never
mind :)

> 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])

Thanks for that, I was wondering if there might be something in
itertools to do this. 

I think the first version is probably more readable though anyway.

More information about the Python-list mailing list