how to print sum of primes in a list in python?

41
February 11, 2019, at 7:20 PM

How do I print sum of primes in a list in Python?

I'm a new to Python, therefore I might be making a terrible mistake. Please help out.

def prime(n):
    i = 2
    c = 0
    for i in range(1,n+1):
        if(n%i == 0):
            c = c+1
    if(c == 2):
        return True
    else:
        return False

def sumprimes(l1):
    l1 = []
    l = len(l1)
    i = 0
    sum = 0
    for i in range(0,l):
        if(prime(l1[i]) is True):
            sum = sum +l1[i]
print(sum)
l1 = [3,4,5,6]
print(sumprimes(l1))

Output should be equal to 8.

Answer 1
def prime(n):
    i = 2
    c = 0
    for i in range(1,n+1):
        if(n%i == 0):
            c = c+1
    if(c == 2):
        return True
    else:
        return False

def sumprimes(l1):
    sum=0
    for x in l1:
        if prime(x):
            sum += x
    return sum
l1 = [3,4,5,6]
print(sumprimes(l1))

Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.

Answer 2

You can do it using below code too.

lst = [1,2,5,7,9,10,12]
def isPrime(x):
    if x == 1:
        return False
    for i in range(2,x-1):
        if x%i == 0:
            return False
    return True

def getPrimeSum(l):
    l = [i for i in l if isPrime(i)]
    return sum(l)
print(getPrimeSum(lst))
READ ALSO
Why Can't I use ResponseEntity<?> annotation with StreamingResponseBody body type?

Why Can't I use ResponseEntity<?> annotation with StreamingResponseBody body type?

I am trying to return a ResponseEntity Object with my Spring Action, the response entity mainly going to be ResponseEntity<StreamingResponseBody>Although if an exception occures I am required to return a response entity which has another type i

48
how to export the contents of a filtered jTable to a pdfpTable

how to export the contents of a filtered jTable to a pdfpTable

I have a JTable and am using JFilter to filter its contents based on user inputNow i intend to export the contents of the JTable to a PdfPTable using iText library

59
How do we solve error 554 5.5.1 (no valid recipients) when using PHP Swiftmailer?

How do we solve error 554 5.5.1 (no valid recipients) when using PHP Swiftmailer?

When testing out our mail server we stumbled accross an error that prevents us from sending mails via PHP, though regular sending/receiving per Mail-in-a-box works without any problemsWe are running a separate Ubuntu 18

33