Lazy List Generator Problem

alex23 wuwei23 at gmail.com
Fri Jan 16 05:42:35 CET 2009


On Jan 16, 12:42 pm, Mark Hahnenberg <ambient.sou... at gmail.com> wrote:
> When I execute this code, the numbers 2,3,4,...,11 are printed (i.e.
> nothing gets filtered out).  Could anyone explain why this is
> happening?  I generally understand generators, and my hypothesis is
> that reassigning to nats the result of filtering nats could be
> screwing things up somehow, but I've tried a variety of other methods,
> from making copies of the old iterator to rolling my own filter
> function and nothing has worked.

Hey Mark,

I think the issue isn't that 'nats' is changing, but that 'elem' is.
Try replacing this:

>       nats = itertools.ifilterfalse(lambda x: x % elem == 0, nats)

with this:

        nats = itertools.ifilterfalse(lambda x, elem=elem: x % elem ==
0, nats)

Which works for me:

In [91]: s = sieve()
In [92]: primes_10 = [s.next() for x in xrange(10)]
In [93]: primes_10
Out[93]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]


Hope this helps.



More information about the Python-list mailing list