下面的代码用于生成素数pythonic吗?
Is the following code for generating primes pythonic?
def get_primes(n): primes=[False,False]+[True]*(n-1) next_p=(i for i,j in enumerate(primes) if j) while True: p=next(next_p) yield p primes[p*p::p]=[False]*((n-p*p)//p+1)请注意,next(next_p)最终将引发StopIteration错误,从而以某种方式结束函数get_primes.不好吗?
Note that next(next_p) will eventually throw a StopIteration error which somehow ends the function get_primes. Is that bad?
还要注意,next_p是一个生成器,它在素数上进行迭代,但是素数在迭代过程中会发生变化.那是不好的风格吗?
Also note that next_p is a generator which iterates over primes, however primes changes during iteration. Is that bad style?
添加以下if语句使前一百万个素数在0.25秒以下:
adding the following if statement gets it under 0.25 seconds for the first million primes:
if p*p<=n: primes[p*p::p]=[False]*((n-p*p)//p+1)推荐答案
next(next_p)抛出StopIteration错误也不错-这是生成器在项目用完时始终会执行的操作!
It's not bad that next(next_p) throws a StopIteration error -- that's what a generator always does when it runs out of items!
在迭代列表时更改列表的长度是一个坏主意.但是,仅更改内容并没有错.总的来说,我认为这是一个相当优雅的(即使是基本的)诱惑.
Changing the length of a list while iterating over it is a bad idea. But there's nothing wrong with simply changing the contents. Overall, I think this is a rather elegant, if basic, seive.
一个小发现:当您划掉"质数的倍数时,如果仔细考虑一下,您会发现不必以p * 2开头.您可以跳到p ** 2.
One small observation: when you "cross out" the multiples of prime numbers, you'll find, if you think about it for a bit, that you don't have to start with p * 2. You can skip ahead to p ** 2.
更多推荐
这是素数生成器pythonic吗
发布评论