这是素数生成器pythonic吗

编程入门 行业动态 更新时间:2024-10-18 14:25:26
本文介绍了这是素数生成器pythonic吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面的代码用于生成素数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吗

本文发布于:2023-11-30 04:25:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648718.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   素数   生成器   pythonic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!