Lazy List Generator Problem

Mark Hahnenberg ambient.sounds at gmail.com
Thu Jan 15 21:42:37 EST 2009


I'm trying to make a lazy, (theoretically) infinite prime number sieve
using generators.  The code I have thus far is:

#!/usr/bin/env python

import itertools

def sieve():
   nats = naturals(2)
   while True:
      elem = nats.next()
      yield elem
      nats = itertools.ifilterfalse(lambda x: x % elem == 0, nats)

def naturals(start=1):
   curr = start
   while True:
      yield curr
      curr += 1

primes = sieve()
i = 0
while i < 10:
   print primes.next()
   i += 1

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.

Thanks,
-MRH



More information about the Python-list mailing list