Concession until all the necessary values ​​are obtained, is there a way to make the slice lazy

Is there any way to stop the change when the generator has not finished the value and all the necessary results have been read? I mean, the generator gives values ​​without even doing StopIteration.

For example, this never stops: (REVISED)

from random import randint
def devtrue():
    while True:
        yield True

answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers

I found this code, but have not yet figured out how to apply it in this case: http://code.activestate.com/recipes/576585-lazy-recursive-generator-function/

+3
source share
4 answers

, , , int:

from time import clock
from random import randint
a=[True for _ in range(randint(1000000,10000000))]
spacing=randint(3,101)
t=clock()
try:
    a[::spacing]=[False]
except ValueError as e:
    a[::spacing]=[False]*int(e.message.rsplit(' ',1)[-1])

print spacing,clock()-t

# baseline

t=clock()
a[::spacing]=[False]*len(a[::spacing])
print 'Baseline:',spacing,clock()-t

, , . Python

0

close() . , GeneratorExit, next() StopIteration:

>>> def test():
...     while True:
...         yield True
... 
>>> gen = test()
>>> gen
<generator object test at ...>
>>> gen.next()
True
>>> gen.close()
>>> gen.next()
Traceback (most recent call last):
  ...
StopIteration
+8

,

TypeError: 'generator' object is unsubscriptable

, devtrue, . , :

def bounded_true(count)
   while count > 0:
       yield True
       count -= 1

:

y = [True] * 5

If you create an infinite generator, it will generate infinitely.

0
source

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

...

0
source

Source: https://habr.com/ru/post/1756324/


All Articles