On 2008-02-12, Paul Hankin <[EMAIL PROTECTED]> wrote: > 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 :).
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. -- http://mail.python.org/mailman/listinfo/python-list