I wrote a simple prime sieve (an unbounded sieve of Eratosthenes) using Python, but for some reason, it isn't working correctly. Here is the sieve:
from itertools import count
def sieve():
nums = count(2)
while True:
n = next(nums)
nums = filter(lambda k: k%n != 0, nums)
yield n
Unfortunately, this isn't working. Instead, it just returns the same values as the count(2) iterator would.
For comparison, this:
nums = count(2)
print(next(nums))
nums = filter(lambda k: k%2 != 0, nums)
print(next(nums))
nums = filter(lambda k: k%2 != 0, nums)
print(next(nums))
will print:
2
3
5
while the sieve function will print:
2 3 4
I thought the issue was with the weird behavior of Python's lambda, but replacing this line:
nums = filter(lambda k: k%n != 0, nums)
with:
def f(k): return k%n != 0
nums = filter(f, nums)
doesn't solve the issue.