question about generators
Jonathan Hogg
jonathan at onegoodidea.com
Thu Aug 15 03:42:49 EDT 2002
On 14/8/2002 22:27, in article yu99wuqtjfls.fsf at europa.research.att.com,
"Andrew Koenig" <ark at research.att.com> wrote:
> You're quite right. I really meant this:
>
> def f():
> for <...>
> if <condition>:
> print <something>
> else:
> <do something>
> f()
> <do something else>
Hmmm... that's a doozy. I'm not sure I'd want to try re-writing that without
recursion. The resulting solution would probably be completely unobvious.
I'd definitely just stick with the 'for x in f(): yield x' convention ;-)
I don't think it's so bad anyway as it reads better for me. Understanding
what a recursive algorithm is doing can be hard at the best of times, but
the for loop makes it explicit there will be multiple results at this point.
With some appropriate naming, it can be quite elegant:
if is_something( node ):
yield node.value
else:
for value in all_sub_somethings_of( node ):
yield value
Well, maybe...
Jonathan
More information about the Python-list
mailing list