Similar to a function takein Haskell, you can create a "limited" generator based on another generator:
def take(n,gen):
'''borrowed concept from functional languages'''
togo=n
while togo > 0:
yield gen.next()
togo = togo - 1
def naturalnumbers():
''' an unlimited series of numbers '''
i=0
while True:
yield i
i=i+1
for n in take(10, naturalnumbers() ):
print n
You can continue this idea with a "do", "bye" generator, ...
def gen_until( condition, gen ):
g=gen.next()
while( not condition(g) ):
yield g
g=gen.next()
And use it like
for i in gen_until( lambda x: x*x>100, naturalnumbers() ):
print i
...
source
share