I'm trying to get all possible combinations that equal a target sum. The script that I have does this perfectly well, however I need the output to show the original index number. The script I have outputs the correct number combinations, but not the correct index.
Example of correct output:
input=([1, 2, 3, 4], target_sum=6)
output=[1,3], [0,1,2]
The code I have is the following (source):
numbers = [1,2,3,4,5]
target = 6
def calc_combo(input_number, target_sum, partial=[]):
total = sum(partial)
idx = []
index = [[num,indices] for indices,num in enumerate(partial)]
if total == target_sum:
for i in index:
idx.append(i)
print(str(idx) + " = " + str(target_sum))
if total >= target_sum:
return
for i in range(len(input_number)):
n = input_number[i]
remaining = input_number[i+1:]
calc_combo(remaining, target_sum, partial + [n])
calc_combo(numbers, target)
Which gives the following output:
[[1, 0], [2, 1], [3, 2]] = 6
[[1, 0], [5, 1]] = 6
[[2, 0], [4, 1]] = 6
Any help is greatly appreciated!