Python 中的埃拉托色尼惰性筛法
我正在尝试用 Python 3.2 编写一个惰性版本的埃拉托斯特尼筛法。代码如下:
import itertools
def primes():
candidates = itertools.count(2)
while True:
prime = next(candidates)
candidates = (i for i in candidates if i % prime)
yield prime
但是,当我迭代 primes() 时,我只得到连续的数字。例如,
print(list(itertools.islice(primes(),0,10)))
打印列表
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
令我惊讶的是,对 primes() 进行以下微小修改使其工作:
def primes():
candidates = itertools.count(2)
while True:
prime = next(candidates)
candidates = (i for i in candidates if i % prime)
next(itertools.tee(candidates)[1]) ########### NEW LINE
yield prime
我猜我错过了有关生成器参数范围的一些内容
candidates = (i for i in candidates if i % prime)
,但我无法看到如何在不添加此随机数的情况下修复代码- 寻找新的线路。有人知道我做错了什么吗?谢谢。
I am trying to code a lazy version of Sieve of Eratosthenes in Python 3.2. Here's the code:
import itertools
def primes():
candidates = itertools.count(2)
while True:
prime = next(candidates)
candidates = (i for i in candidates if i % prime)
yield prime
However, when I iterate over primes(), I only get consecutive numbers. E.g.,
print(list(itertools.islice(primes(),0,10)))
prints the list
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
To my surprise, the following tiny modification of primes() makes it work:
def primes():
candidates = itertools.count(2)
while True:
prime = next(candidates)
candidates = (i for i in candidates if i % prime)
next(itertools.tee(candidates)[1]) ########### NEW LINE
yield prime
I am guessing I am missing something about the scope of the parameters of the generator
candidates = (i for i in candidates if i % prime)
but I cannot see how to fix the code without adding this random-looking new line. Does anybody know what I am doing wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
修复实际上是将: 替换
为:
the fix is really to replace:
with:
如果您担心变量的范围,请创建对象/函数来为您保留这些变量:(
我现在无法访问 Pytho 解释器,所以我不知道这最终是否真的有效,或者不是...)
顺便说一句,您使用的算法并不是真正的埃拉斯托尼筛法。如果您有时间,请查看这篇很酷的论文:http:// /www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
If you are worried about the scope of the variables, create objects/functions to keep these variables for you:
(I don't have access to a Pytho interpreter right now, so I don't konw if this actually works in the end or not...)
BTW, the algorithm you use is not really the sieve of Erastothenes. Take a look in this cool paper if you have some time: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
下面是基于论文中的 haskell 代码的真正素数筛的 Python 实现: The Genuine Sieve of Eratosthenes by Melissa E. O'Neill
它不使用递归或试除法,但相当消耗内存。
打印内容如下
:
Here is a Python implementation of the genuine prime sieve based on the haskell code in the paper: The Genuine Sieve of Eratosthenes by Melissa E. O'Neill
It does not use recursion or trial division but is rather memory hungry.
The following:
prints: