给定元素长度的Python子集总和问题

时间:2019-03-03 03:53:20

标签: python subset subset-sum

对于给定的集合,元素的总和和长度,
我想获取布尔值是否满足条件

例如...

Input : set = [18,0,2,20], sum = 20, length = 2 <br>
Output : True (subset [18,2] satisfy the sum=20 for given length 2)

Input : set = [18,0,2,20], sum = 22, length = 1 <br>
Output : False

如果存在给定的长度限制,如何解决该问题?
(如果没有长度条件,我可以轻松解决: subset-sum-problem

def isSubsetSum(set, n, sum):
    if sum == 0:
        return True
    if (sum != 0) and (n == 0):
        return False
    if (set[n-1] > sum):
        return isSubsetSum(set,n-1,sum)
    # (a) including the last element
    # (b) excluding the last element
    # Not "AND", But "OR" !!!!!
    return isSubsetSum(set,n-1,sum) or isSubsetSum(set,n-1,sum-set[n-1])

2 个答案:

答案 0 :(得分:0)

如果允许使用导入的模块,则itertools具有组合功能,可以使此操作非常简单:

from itertools import combinations
set    = [18,0,2,20]
total  = 20
length = 2
result = [ c for c in combinations(set,length) if sum(c) == total ]
if result: 
  print("True, subset ",result[0],"satisfies the sum", total, "given length",length)
else: 
  print("False")

如果需要将其用作递归函数,请考虑对于集合中的每个元素X,如果可以在后续元素中找到N-1个元素的子集,而这些元素合计{{1} },您有一个sum-X的解决方案。

例如:

sum/length=N

答案 1 :(得分:0)

使用requests

itertools.combinations