Deneb
Deneb

Reputation: 1061

Can someone explain this prime list generator for me?

This is apparently a very fast prime list generator ( Fastest way to list all primes below N), but I can't understand some parts of it, mostly because of the syntax.

def rwh_primes1(n): 
    """ Returns  a list of primes < n """
    sieve = [True] * (n/2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i/2]:
            sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

Why sieve is defined as [True] (a boolean) multiplied by an integer?

What means if sieve[i/2]?

What means sieve[i*i/2::i], especially the ::i part?

Upvotes: 1

Views: 113

Answers (1)

will
will

Reputation: 10650

looks like it's just array notation you're looking for.

[a] * 5 just becomes [a,a,a,a,a]

if sieve[i/2] is checking if the value of sieve at i/2 is True or False

and the :: defines the stride.

see this answer.

Upvotes: 1

Related Questions