Agarwal Prega Agarwal Prega - 4 months ago 36
Python Question

How to calculate sum of prime numbers from list of integers in Python?

I am struck and need help with this..
I want to find the sum of prime numbers from a given list of integers. Here are a few test cases for the same.

n([3,3,1,13])

19

n([2,4,6,9,11])

13

n([-3,0,1,6])

0


The Code that I have written is as follows but it fails with the test cases above..

def sumprimes(n):
sum1 = 0
for i in range(0,len(n)):
num = n[i]
if num > 1:
for j in range(2, int(num**0.5)+1):
if num%j != 0:
sum1 = sum1 + num
else:
sum1 = 0
return(sum1)

Answer

This part is wrong:

        for j in range(2, int(num**0.5)+1):
            if num%j != 0:
                sum1 = sum1 + num

you are summing num for each number in the range that didn't divide. you should sum just if all of them didn't divide.

Simple way to do this is:

        prime = True
        for j in range(2, int(num**0.5)+1):
            if num%j == 0:
                prime = false
                break
        if prime:
            sum1 = sum1 + num

Or in a more pythonic way using all():

        if all(num%j != 0 for j in range(2, int(num**0.5)+1)):
            sum1 = sum1 + num