Note that there are some explanatory texts on larger screens.

plurals
  1. POMerged iterators produce obscure results
    primarykey
    data
    text
    <p>I'm trying to implement prime number generator using <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenes</a> algorithm. I do it just to try using recursive <a href="https://stackoverflow.com/a/465043/862380">iterator merging</a> to implement sifter.</p> <p>What I do is this:</p> <pre><code>from itertools import count,islice,groupby from heapq import merge def primes3(): p = 2 yield p sifter = (i*p for i in count(p)) s = next(sifter) for p in count(p+1): if p==s: # this p is sieved out print('s: {}'.format(s)) s = next(sifter) else: yield p # this is prime print('p: {}'.format(p)) sifter = (k for k, g in groupby(merge(sifter,(i*p for i in count(p))))) #add this serie to the sifter: p*p, p*(p+1), p*(p+2), ... print(list(islice(primes3(),10))) </code></pre> <p>The output is:</p> <pre><code>p: 3 s: 4 p: 5 p: 6 p: 7 p: 8 p: 9 p: 10 p: 11 s: 12 [2, 3, 5, 6, 7, 8, 9, 10, 11, 13] </code></pre> <p>The first number to be sieved out is <code>4</code>. But the next is <code>12</code>, not <code>6</code> as it should be. Why is that? I checked it with the following code:</p> <pre><code>&gt;&gt;&gt; sifter = (i*2 for i in count(2)) &gt;&gt;&gt; next(sifter) 4 &gt;&gt;&gt; sifter = (k for k, g in groupby(merge(sifter,(i*3 for i in count(3))))) &gt;&gt;&gt; print(list(islice(sifter,20))) [6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 26, 27, 28, 30, 32, 33, 34] </code></pre> <p>So, as we may see, in test conditions sifter yields the correct results.</p> <p>Where am I making a mistake? I think it must be something trivial that I just don't see.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload