I'd like to modify the subset_sum()
python function from Finding all possible combinations of numbers to reach a given sum so that:
- It allows repeats (permutations) instead of combinations
- It only considers permutations of a given length
I've successfully accomplished #2, but I need assistance with #1:
def subset_sum(numbers, target, length, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target and len(partial) == length:
print(f"sum({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, length, partial + [n])
The desired output should be:
>>> subset_sum([3,9,8,4,5,7,10],target=15,length=3)
sum([3, 8, 4])=15
sum([3, 4, 8])=15
sum([4, 3, 8])=15
sum([4, 8, 3])=15
sum([8, 3, 4])=15
sum([8, 4, 3])=15
sum([3, 5, 7])=15
sum([3, 7, 5])=15
sum([5, 3, 7])=15
sum([5, 7, 3])=15
sum([7, 3, 5])=15
sum([7, 5, 3])=15