简体   繁体   English

使用递归查找总和相等的情况

[英]Using recursion to find cases where sum is equal

def subset_sum(numbers, target, partial=[]):
s = sum(partial)

# check if the partial sum is equals to target
if s == target: 
    print "sum(%s)=%s" % (partial, target)
if s >= target:
    return  # if we reach the number why bother to continue

for i in range(len(numbers)):
    n = numbers[i]
    remaining = numbers[i+1:]
    subset_sum(remaining, target, partial + [n]) 

The above code is supposed to check how many times a certain target sum can be obtained from a list. 上面的代码应该检查从列表中可以获取某个目标总和的次数。

How may I modify it to use recursion to check the number of times the sums of any combination of numbers in the list are equal? 我如何修改它以使用递归检查列表中任何数字组合的总和相等的次数? For example, [1, 2, 3] should give an output of 2 since 1+2=3 and 3= 2+1 and [1, 1, 2, 3, 5] should give 4. 例如,[1,2,3]应该给出2的输出,因为1 + 2 = 3和3 = 2 + 1,而[1,1,2,3,5]应该给出4。

Something like this should work: 这样的事情应该起作用:

def subset_sum(target, remaining, partial=()):
    remaining = tuple(remaining)
    if remaining == ():
        return 1 if sum(partial) == target else 0
    else:
        return (subset_sum(target, partial, remaining[1:]) + 
                subset_sum(target, partial + remaining[:1], remaining[1:]))

>>> subset_sum(5, [1,1,2,3,5])
3
>>> subset_sum(2, [1,1,2,3,5])
2

We use tuples here do we don't have to worry about multiple references to the same list interfering with each other. 我们在这里使用元组,我们不必担心对同一列表的多个引用会相互干扰。 Tuples are immutable so any "modifications" won't spill into other instances. 元组是不可变的,因此任何“修改”都不会溢出到其他实例中。

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

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