2.2 features
Tom Good
Tom_Good1 at excite.com
Fri Jul 27 16:55:49 EDT 2001
cjc26 at nospam.cornell.edu (Cliff Crawford) wrote in message news:<pRW77.126602$EF2.17425212 at typhoon.nyroc.rr.com>...
> * Tom Good <Tom_Good1 at excite.com> menulis:
> |
> | #------ begin code
> |
> | def genWhile(g, condition):
> | """
> | run generator g while 'condition' is true.
> | Condition is a partial expression string such as "< 10"
> | to be evaluated with g.next() as the left side
> | """
> | while 1:
> | next = g.next()
> | if eval("next " + condition):
> | yield next
> | else:
> | raise StopIteration
> |
> | #------ end code
> |
> | Then you can say, for example:
> |
> | >>> g = fib()
> | >>> [x for x in genWhile(g, "< 50")]
> |
> | [1, 1, 2, 3, 5, 8, 13, 21, 34]
> |
> | ...to get the Fibonacci numbers that are less than 50.
>
> This is neat, but I think passing in a function to test the condition
> would be cleaner than passing in a string. Like this:
>
> def genWhile(g, condition):
> while 1:
> next = g.next()
> if condition(next):
> yield next
> else:
> return
>
> [x for x in genWhile(fib(), lambda f: f < 50)]
You are right, that is a good way! I wrote the string based version,
then thought of that solution afterwards.
Tom
More information about the Python-list
mailing list