I wrote a simple right-handed sieve (unlimited Eratosthenes sieve) using Python, but for some reason it does not work correctly. Here is a 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 does not work. Instead, it simply returns the same values ββas the count (2) iterator.
For comparison:
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 problem was due to the strange behavior of Python 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)
does not solve the problem.
source share