2012-06-28 60 views
2

我在执行“Eratosthenes筛选”时出现错误,以获取指定范围内的所有素数。我知道我的代码还没有素检,我会在解决错误后添加它们。实施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) 

错误:

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 
+0

有关使用'set'做一个筛子的示例:http://stackoverflow.com/a/9302299/5987 –

回答

2

你不能通过索引引用一个集合元素,但set是可迭代的,所以这个:

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

可以改写为:

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

+1。如果你因为某种原因需要索引,你可以在“枚举(池)”中做“。但值得指出的是,虽然这解决了他的错误,但它并没有使他的算法发挥作用。正如BrenBam指出的那样,一组中的元素是无序的,但OP似乎认为他会首先获得最小的素数。 – abarnert

2

错误正是它说:集不通过索引支持个别项目的检索。它看起来像你想用一个列表或x范围对象,而不是(例如,pool = xrange(l, r+1)。你为什么要使用一套?

注意,在集合中的元素是无序的,所以遍历他们的方式你你不能假定更大的素数将在集合的“末尾”

+0

我使用了这个设置,这样我就可以直接区分池中素数的倍数数字。 –