我在python中使用了Eratosthenes的筛子来生成素数,人们吹捧它是一个相对快速的选择,比如一些the answers to a question on optimising prime number generation in python中的解决方案并不简单,而且我在这里的简单实现在效率上与它们竞争。我的实现如下def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return sieve
print [2] + [i*2+1 for i, v in enumerate(sieve_for_primes_to(10000000)) if v and i>0]
定时执行返回python -m timeit -n10 -s "import euler" "euler.sieve_for_primes_to(1000000)"
10 loops, best of 3: 19.5 msec per loop
而在对上述链接问题的回答中描述的方法是python食谱中最快的,如下所示import itertools
def erat2( ):
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def get_primes_erat(n):
return list(itertools.takewhile(lambda p: p
当它运行时python -m timeit -n10 -s "import euler" "euler.get_primes_erat(1000000)"
10 loops, best of 3: 697 msec per loop
我的问题是,为什么人们会在相对复杂的《烹饪》一书中大肆宣扬这一点?