带有ipython的意外TypeError

时间:2013-06-26 07:18:16

标签: python ipython typeerror

昨天我做了以下程序,它在带有 IPython Interpreter 的Spyder IDE for Windows中运行没有任何错误。但是今天我不知道发生了什么,它给我一个错误。所以,我也在Spyder IDE中为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解释器外部系统终端中执行此操作时,它会成功执行

1 个答案:

答案 0 :(得分: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