昨天我做了以下程序,它在带有IPython Interpreter的 Spyder IDE for Windows 中运行没有任何错误。但是今天我不知道发生了什么,它显示了一个错误。所以,我也在 Spyder IDE for Ubuntu 中尝试了这个,但它显示了同样的错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 487, in runfile
execfile(filename, namespace)
File "C:\Users\BK\.spyder2\.temp.py", line 23, in <module>
print sum_prime(2000000)
File "C:\Users\BK\.spyder2\.temp.py", line 21, in sum_prime
return sum(suspected) + sum_p
TypeError: unsupported operand type(s) for +: 'set' and 'int'
程序:
import math
def is_prime(num):
if num < 2: return False
if num == 2: return True
if num % 2 == 0: return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0: return False
return True
def sum_prime(num):
if num < 2: return 0
sum_p = 2
core_primes = []
suspected = set(range(3, num + 1, 2))
for i in range(3, int(math.sqrt(num)) + 1, 2):
if is_prime(i): core_primes.append(i)
for p in core_primes:
sum_p += p
suspected.difference_update(set(range(p, num + 1, p)))
return sum(suspected) + sum_p
print sum_prime(2000000)
但是当我在专用的 python 解释器或外部系统终端中执行它时,它会成功执行。