Infinite lists and generators
Terry Reedy
tjreedy at home.com
Wed Nov 14 12:39:32 EST 2001
"Steven D. Majewski" <sdm7g at Virginia.EDU> wrote in message
news:mailman.1005757000.20449.python-list at python.org...
>
>
> On Wed, 14 Nov 2001, Terry Reedy wrote:
> > The problem with filtering an infinite stream is that if there are
> > only N items that pass, the filter will never halt looking for the
> > N+1st.
>
> You just do 'lazy' filtering -- in fact you try to avoid forcing
> evaluation of the whole stream until the very end, and then you
> stop when you get a sufficient number, or reach the end of the
> stream.
The topic was infinite streams that have no end!
> ( And if possible, you may not have to force full evaluation
> at all if you can do your output one item at a time. You should
> avoid list comprehensions though, which force evaluation -- kind
> of like Icon's 'every' )
>
> Filter is just:
>
> def filter( f, stream ):
> for item in stream:
> if f(item): yield item
This is what I had in mind when I wrote my comment. To illustrate,
try
def n_true(n):
if n < 0: raise StopIteration
while n:
yield n
n -= 1
while 1:
yield 0
for item in filter(lambda x: x, n_true(10)): print item
Terry J. Reedy
More information about the Python-list
mailing list