Reputation: 2441
Yesterday I did the following program and it was running without any error in the Spyder IDE for Windows with IPython Interpreter. But today I don't know what happened it showing me an error. So, I also tried this in the Spyder IDE for Ubuntu but it shows the same error.
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'
Program:
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)
But it executes successfully when I execute this in dedicated python interpreter or external system terminal.
Upvotes: 2
Views: 263
Reputation: 80426
You are using numpy.core.fromnumeric.sum
not the python builtin function (IPython is importing it behind the scenes):
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
You can fix this by making sure you are using the "right sum" :
import __builtin__
sum = __builtin__.sum
Upvotes: 1