2

昨天我做了以下程序,它在带有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 解释器外部系统终端中执行它时,它会成功执行。

4

1 回答 1

1

您使用numpy.core.fromnumeric.sum的不是 python 内置函数(IPython 在幕后导入它):

In [1]: sum
Out[1]: <function numpy.core.fromnumeric.sum>

In [2]: sum({1,2,3,4})
Out[2]: set([1, 2, 3, 4])  # returns a set

In [3]: del sum

In [4]: sum({1,2,3,4})
Out[4]: 10

您可以通过确保使用“正确的总和”来解决此问题:

import __builtin__
sum = __builtin__.sum
于 2013-06-26T07:24:38.547 回答