根据指定值评估集合中所有可能的值组合

Evaluate all possible combinations of values in a set against a specified value

我有一个家庭作业问题,要求我编写一个函数,给定一个整数 k 和 n 个无序整数的列表 A,确定 A 总和为 k.

我正在努力获得评估列表中值的所有可能组合的函数。一旦它得到一个总和不等于 k ​​的对,它就会停止。如果有人有任何建议/提示,我将不胜感激。我不是在寻找直接的答案,只是在寻找正确的方向。

这是我目前的情况:

def sumsToK(k, list1):
    newSet = set(list1) #creates set based on list1 to remove any duplicate values
    print (newSet)
    newSet = list(newSet) #convert back to list so I can iterate through values
    for i in range(len(newSet)):
        for j in range(i+1, len(newSet)):
            print(newSet[i],newSet[j])
            if (newSet[i]) + (newSet[j]) == k:
                return (print('There is at least one pair if integers that adds up to k'))
            else:
                return(print('There are is no pair of distinct integers that adds up to k'))

k = 9
list1 = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10] #Multiple distinct pairs will sum to 9

print ((sumsToK(k, list1)))

As soon as it gets a pair that does not sum to k it stops

根据您的代码这是正常的:您在第一次迭代时立即 return,无论您是否找到一对。

删除第二个 return,一切就绪:

def sumsToK(k, list1):
    newSet = set(list1) #creates set based on list1 to remove any duplicate values
    print (newSet)
    newSet = list(newSet) #convert back to list so I can iterate through values
    for i in range(len(newSet)):
        for j in range(i+1, len(newSet)):
            print(newSet[i],newSet[j])
            if (newSet[i]) + (newSet[j]) == k:
                return('There is at least one pair if integers that adds up to k')
            else:
                # it's important not to return anything here otherwise you
                # exit the loop :)
                print('This is not a pair of distinct integers that adds up to k')

k = 9
list1 = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10] #Multiple distinct pairs will sum to 9

print ((sumsToK(k, list1)))

它给了我:

set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
(1, 7)
(1, 8)
There is at least one pair if integers that adds up to k

顺便说一下,不要 return print 语句,只是 return 字符串,或 print 它(不是两者!)。