0

所以这是我到目前为止的代码。如果总和存在,它会起作用并返回true,但我似乎无法找到一种方法来打印出它用来查找总和的整数。有没有办法我可以重新编写它以使其与 true 一起做到这一点,或者我应该如何编写代码以便它可以做到这一点?

from itertools import combinations

def com_subset_sum(seq, target):
    if target == 0 or target in seq:
        return True

    for r in range(2, len(seq)):
        for subset in combinations(seq, r):
            if sum(subset) == target:
                return True
    return False 
4

2 回答 2

1

只是print用来查看它的内容:

例子:

from itertools import combinations

def com_subset_sum(seq, target):
    if target == 0 or target in seq:
        return True

    for r in range(len(seq),1,-1):
        for subset in combinations(seq, r):
            if sum(subset) == target:
                print subset
                return True
    return False


print com_subset_sum([1,3,5,1,6,8,7],10)

输出:

(1, 3, 5, 1)
True
于 2013-04-17T20:23:40.840 回答
0

怎么样的东西

def ssum(numbers, target):
    return [x for r in xrange(2,len(numbers)) for x in combinations(numbers,r) if sum(x)==target]
于 2013-04-17T20:56:46.680 回答