On Feb 12, 11:15 am, Ben C <[EMAIL PROTECTED]> 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
--
http://mail.python.org/mailman/listinfo/python-list