Lazy List Generator Problem
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.
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)
nats = itertools.ifilterfalse(lambda x, elem=elem: x % elem ==
Which works for me:
In : s = sieve()
In : primes_10 = [s.next() for x in xrange(10)]
In : primes_10
Out: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Hope this helps.
More information about the Python-list