如何从Python中的整数列表计算素数之和?

时间:2016-08-02 22:07:26

标签: python python-3.x

我很震惊,需要帮助。 我想从给定的整数列表中找到素数之和。以下是一些相同的测试用例。

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

19

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

13

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

0

我编写的代码如下,但上述测试用例失败了。

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)

10 个答案:

答案 0 :(得分:5)

这部分错了:

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

您正在为未分割范围内的每个数字求和num。 如果所有他们没有分裂,你应该总结。

这样做的简单方法是:

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

或使用all()

的更多 pythonic 方式
        if all(num%j != 0 for j in range(2, int(num**0.5)+1)):
            sum1 = sum1 + num

答案 1 :(得分:1)

请勿尝试在一个功能中执行所有操作。我把剩下的逻辑分开了,但我会把isprime留给你:

def isprime(x):
    # Replace this with your code
    # separate function so it can have its own tests
    return x in [3, 13, 11, 2]

def sum_prime_numbers_in_list(l):
    return sum([x for x in l if isprime(x)])

if 19 != sum_prime_numbers_in_list([3, 3, 1, 13]):
    raise ValueError
else:
    print 'pass'

if 13 != sum_prime_numbers_in_list([2, 4, 6, 9, 11]):
    raise ValueError
else:
    print 'pass'

if 0 != sum_prime_numbers_in_list([-3, 0, 1, 6]):
    raise ValueError
else:
    print 'pass'

答案 2 :(得分:1)

def sumprimes(n):
    s=0
    f=[]
    for i in range (0,len(n)):
        num=n[i]
        if num>1:
            f=[]
            for j in range (1,num+1):
                if num%j==0:
                    f=f+[j]
                if f==[1,num]:
                    s=s+num
    return(s) 

答案 3 :(得分:0)

答案应该是这个。 [您应该在此链接中尝试此代码。Gist]

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

答案 4 :(得分:0)

> def sumprimes(n):
    sum=0
    fact=[]
    for i in range (0,len(n)):
        num=n[i]
        if num>1:
            fact=[]
            for j in range (1,num+1):
                if num%j==0:
                    fact=fact+[j]
        if fact==[1,num]:
            sum=sum+num


    return(sum)

答案 5 :(得分:0)

def isPrime(n):
    if (n<2):
        return False
    for i in range (2,n):
        if (n%i==0):
            return False
    return True

li = []
a = [1,10,11,12,13]
for x in a:
    if isPrime(x):
        li.append(x)

print(li)

total = 0
for j in range(len(li)):
    total += li[j]

print(total)    

答案 6 :(得分:0)

lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
lst=[]
print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):

   if num > 1:
       for i in range(2,num):
           if (num % i) == 0:

               break
       else:
           print(num)
           lst.append(num)
print(lst)
sum=0
for i in lst:
    sum=sum+i
print('sum of all prime numbers=%d'%sum)

答案 7 :(得分:0)

def sum_primes(a):
    sum = 0
    for num in a:  
       if num > 1:  
           for i in range(2,num):  
               if (num % i) == 0:  
                   break  
           else:  
               sum = sum + num
    if sum < 1:
        print("sum_primes(" + str(a) + ") --> " + "None")
    else:
        print("sum_primes(" + str(a) + ") --> " + str(sum))
sum_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
sum_primes([2, 3, 4, 11, 20, 50, 71])
sum_primes([])

#code by Rushabh Koradia

答案 8 :(得分:-1)

s=input("Enter :")
arr=s.split(",")
sum=0
for f in range(2,(len(arr)+1)):
   k=0
   for i in range(2,f//2+1):
      if (f%(int(arr[i]))==0):
        k=k+1
if(k<=0):
    sum=sum+f
print("Sum :",sum)

答案 9 :(得分:-2)

L = [11,14,13,12,60,50,1]

for a in L:

    if(a % 2 == 0):

     L.remove(a)

for a in L:

    if (a % 3 == 0):

     L.remove(a)

print(sum(L))