2

For given set, and sum, and length of elements,
I want to get the boolean value whether the set satisfy the condition

For example...

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

How can I solve the problem if there is a given length constraint?
(I can solve it easily if there is no length condition: 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])
Jab
  • 26,853
  • 21
  • 75
  • 114
MTHL
  • 123
  • 5

2 Answers2

1

If you're allowed to use imported modules, itertools has a combinations function that can make this quite easy:

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")

If you need it to be a recursive function, consider that for each element X in the set, if you can find a subset of N-1 elements in the subsequent elements that total sum-X, you have a solution for sum/length=N.

For example:

def subSum(numbers,total,length):
  if len(numbers) < length or length < 1:
    return []
  for index,number in enumerate(numbers):
    if length == 1 and number == total:
      return [number]
    subset = subSum(numbers[index+1:],total-number,length-1)
    if subset: 
      return [number] + subset
  return []
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Use itertools.combinations:

from itertools import combinations

inp = [18,0,2,20]
length = 2
sum_ = 20

def isSubsetSum(data, length, sum_):
    data = [i[0]+i[1] for i in combinations(data,length)]
    if sum_ in data:
        return True
    return False

print(isSubsetSum(inp,length, sum_))
Sociopath
  • 13,068
  • 19
  • 47
  • 75