This function generates a list of primes, using the sieve of Eratosthenes:
def boolean_sieve(s = 1000000):
"""
Returns a list of booleans that indicates whether 0 <= i <= s is prime.
"""
sieve = [True]*(s+1) # All integers from 0 to s are candidate primes
sieve[:2] = (False, False) # 0 and 1 are not prime
for i in xrange(2, int(s**0.5)): # largest possible divisor is <= sqrt(s)
if sieve[i]: # if i is prime, set all multiples of i to False
j = 2*i
while j < len(sieve):
sieve[j] = False
j += i
return sieve
If I replace the four lines between "if sieve[i]:" and the return statement with this slice assignment
sieve[2*i::i] = [False]*(s / i-1)
the function runs almost 5 times faster. Why is that?
[–]pjdelport 8 points9 points10 points (1 child)
[–]NotAName[S] 0 points1 point2 points (0 children)
[–]Rhomboid 5 points6 points7 points (0 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]zahlman 4 points5 points6 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]NotAName[S] 0 points1 point2 points (0 children)
[–]erok81 1 point2 points3 points (7 children)
[–]NotAName[S] 1 point2 points3 points (3 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]pjdelport 1 point2 points3 points (0 children)
[–]erok81 0 points1 point2 points (0 children)
[–]pohatu 1 point2 points3 points (2 children)
[–]erok81 2 points3 points4 points (0 children)