简体   繁体   English

如何在 python 的数组中找到非主索引值的总和?

[英]How to find sum of non-prime index values in an array in python?

Input:
-1,-2,-3,3,4,-7
Output:
1 
Explanation : The values at the non-prime index are-1,-2,4 and their sum is 1

CODE:代码:

no=int(input("ENTER :"))
def sumDigits(no): 
    return 0 if no == 0 else int(no%10) + sumDigits(int(no/10))  


print(sumDigits(no)) 

My code just gives sum of all digits.我的代码只是给出所有数字的总和。 How to find sum of non-prime index values in an array?如何在数组中找到非主索引值的总和?

in your code, you need to check that index are primes or not, if it not then add the value else continue在您的代码中,您需要检查索引是否为素数,如果不是,则添加该值,否则继续

def primes(n): # simple Sieve of Eratosthenes 
    odds = range(3, n+1, 2)
    sieve = set(sum([list(range(q*q, n+1, q+q)) for q in odds],[]))
    return [2] + [p for p in odds if p not in sieve]


l = [-1,-2,-3,3,4,-7]

length = len(l)

prime = primes(length)
sol = 0

for i, v in enumerate(l):
    if i not in prime:
        sol += v

print(sol) # output 1

You could use a library to help, such as sympy您可以使用库来提供帮助,例如 sympy

import sympy
l = [-1,-2,-3,3,4,7]
sum([l[x] for x in range(len(l)) if not sympy.isprime(x)])

Output Output

1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM