实施Eratosthenes筛选时出错

时间:2012-06-28 04:18:35

标签: python

我在实施'Eratosthenes筛选'时遇到错误,以获得指定范围之间的所有素数。我知道我的代码还没有素数检查,我会在解决错误后添加它们。

def foo(l,r):
    if l == r:
        return "Error"
    if l > r:
        return "Error"
    if l < r:
        pool = set(xrange(l,r + 1))
        prime = 2
        if l == 1:
            print "Discard 1 for now"
        while prime <= r:
            rem = set(xrange(prime,r + 1,prime))
            pool.difference_update(rem)
            a = 0

            while prime >= pool[a]:
                a = a + 1
            prime = pool[a]
        print pool

foo(1,31623)

ERROR:

Traceback (most recent call last):
  File "D:\code\sieve_of_eratothenes.py", line 32, in <module>
    foo(1,31623)
  File "D:\code\sieve_of_eratothenes.py", line 27, in foo
    while prime >= pool[a]:
TypeError: 'set' object does not support indexing

2 个答案:

答案 0 :(得分:2)

错误恰如其分:设置不支持通过索引检索单个项目。看起来您想要使用列表或xrange对象(例如,pool = xrange(l, r+1)。为什么使用集合?

请注意,集合中的元素是无序,因此按照您尝试的方式迭代它们将无法正常工作。你不能假设更大的素数将在集合的“结束”。

答案 1 :(得分:2)

您不能通过索引引用set元素,但set是可迭代的,所以:

a = 0
while prime >= pool[a]:
   a = a + 1
   prime = pool[a]

可以改写为:

for el in pool:
   if prime >= el:
       prime = el
       break