从给定列表中添加整数

问题描述 投票:-1回答:3

我有一个问题:给定一个数字列表和一个数字k,返回列表中的任何两个数字是否加起来为k

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

如何在整数列表中添加一些元素?

其中我写的代码是:

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

while i < k:
    if i + i != k:
        return False
    else:
        return True
python list
3个回答
0
投票

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

为了提高性能,最好将列表转换为dict,计算输入中每​​个数字出现的次数。 (列表有O(n)成员资格测试,而dicts有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
投票

你可以使用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

-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.')
© www.soinside.com 2019 - 2024. All rights reserved.