2.2 features
Cliff Crawford
cjc26 at nospam.cornell.edu
Thu Jul 26 11:40:05 EDT 2001
* 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)]
--
Cliff Crawford http://www.sowrong.org/
A sign should be posted over every campus toilet:
"This flush comes to you by courtesy of capitalism."
-- Camille Paglia
More information about the Python-list
mailing list