将给定列表中的整数相加

时间:2019-03-24 10:58:47

标签: python list

我有一个问题:给定一个数字列表和一个数字k,请返回列表中是否有两个数字加起来等于k

例如,给定[10, 15, 3, 7]k为17,则由于10 + 7为17,因此返回true。

如何将整数列表中的某些元素加在一起?

我写的代码是:

a = [10, 15, 3, 7]
k = 17

while i < k:
    if i + i != k:
        return False
    else:
        return True

3 个答案:

答案 0 :(得分:0)

对于列表中的每个数字num,计算k - num并检查列表中是否存在该数字。

为了提高性能,最好将列表转换成dict,以计算每个数字在输入中出现的次数。 (列表具有O(n)个成员资格测试,而字典具有O(1)个。)

a = [10, 15, 3, 7]
k = 17

from collections import Counter

occurences = Counter(a)  # count how many times each number occurs

for num in a:
    complement = k - num

    if complement not in occurences:
        continue

    # if the number is its own complement, check if it
    # occurred at least twice in the input
    if num == complement and occurences[num] < 2:
        continue

    print('The pair {} + {} adds up to {}'.format(num, complement, k))
    break
else:
    print('No combination of two numbers adds up to {}.'.format(k))

答案 1 :(得分:-1)

这需要工作,但是,这是一个非常慢的代码:

a = [10, 15, 3, 7]
k = 17
done = False #define a flag
#use two for loops to check if two numbers add up to k
for i in a: 
    for p in a:
        if i + p == k:
            print(str(i) + '+' + str(p) + '=' + str(k))
            done = True
            break #to break out of inner loop
    if done:
        break #to break out of outer loop
if done == False:
    print('No such numbers exist.')

答案 2 :(得分:-1)

您可以将any()itertools.combinations结合使用:

from itertools import combinations

def sum_available(lst, k):
    return any(x + y == k for x, y in combinations(lst, 2))

用法

>>> a = [10, 15, 3, 7]
>>> k = 17
>>> sum_available(a, k)
True