Please help.
I found a couple of code examples that partially do what I need (see below). Can you please help me modify either code to do what I need?
I need to find all the combinations in a list of numbers and to each combination to substract (or add, multiply, or divide) a value AND then to find which result sums to a specific value.
For example:
- Here is a number list: 10, 12, 3, 4, 8
- And here is the value I want to substract from each combination: 5
- And here is the final target value (product) to find (only the combinations that give this result should be printed): 7
So the computation should be (I’m giving only the general idea since the actual list could be potentially longer):
10 - 5 = 5
10 + 12 - 5 = 17
10 + 12 + 3 - 5 = 20
10 + 12 + 3 + 4 - 5 = 24
10 + 12 + 3 + 4 + 8 - 5 = 32
12 - 5 = 7
12 + 3 - 5 = 10
12 + 3 + 4 - 5 = 14
12 + 3 + 4 + 8 - 5 = 22
3 - 5 = -2
3 + 4 - 5 = 2
3 + 4 + 8 - 5 = 10
4 - 5 = -1
4 + 8 - 5 = 7
And the only combinations that should “print” are:
12 - 5 = 7
4 + 8 - 5 = 7
Here are the two sample codes that I found and partially do what I need:
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])
if __name__ == "__main__":
subset_sum([10, 12, 3, 4, 8], 7)
and the second one:
class Solution(object):
def combinationSum(self, candidates, target):
result = []
unique={}
candidates = list(set(candidates))
self.solve(candidates,target,result,unique)
return result
def solve(self,candidates,target,result,unique,i = 0,current=[]):
if target == 0:
temp = [i for i in current]
temp1 = temp
temp.sort()
temp = tuple(temp)
if temp not in unique:
unique[temp] = 1
result.append(temp1)
return
if target <0:
return
for x in range(i,len(candidates)):
current.append(candidates[x])
self.solve(candidates,target-candidates[x],result,unique,i,current)
current.pop(len(current)-1)
ob1 = Solution()
print(*ob1.combinationSum([10, 12, 3, 4, 8],7), sep='\n')
In advance, thank you for any help provided. I’m new to Python as you can tell.