Combinations of different coin nominations summed to a target value using itertools
You need to use combinations
instead of combinations_with_replacement
, so your count
checks can be omitted.
Also, why do you check only combinations of length 8? You should check any from 0
to len(all_coins)
, that's why there should be nested for loop (see more examples of all possible combinations here)
Final code might be:
import itertools
ones = [1, 1, 1] # 3 coins of 1
twos = [2, 2] # 2 coins of 2
fives = [5, 5, 5] # 3 coins of 5
target = 3
all_coins = ones + twos + fives
res = set()
for coins_to_take in range(len(all_coins)+1):
for c in itertools.combinations(all_coins, coins_to_take):
if sum(c) == target:
res.add(c)
for r in res:
print(r)