我在執行「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
有關使用'set'做一個篩子的示例:http://stackoverflow.com/a/9302299/5987 –