If I have 3 types of coins (one, two, and five). I have different amounts of each coin. How can I get all combinations equal to a certain target?
For example:
one = [1, 1, 1] # 3 coins of 1
two = [2, 2] # 2 coins of 2
five = [5, 5, 5] # 3 coins of 5
target = 10
Using this code:
s = set()
one = 3
two = 2
five = 5
for c in combinations_with_replacement((0,1,1,1,2,2,5,5,5), 8):
if sum(c) == target:
s.add(c)
for c in s:
if c.count(1) <= one and c.count(2) <= two and c.count(5) <= five:
print(f"{c.count(1)} * one + {c.count(2)} * two + {c.count(5)}* five = 10")
Gave these combinations with sum of target:
3 * one + 1 * two + 1 * five = 10
0 * one + 0 * two + 2 * five = 10
1 * one + 2 * two + 1 * five = 10
However, I don't feel this is the best approach, how can this be solved in a more elegant way?
The question is for using itertools
, collections
, or other modules to simplify that task.
No nested for
loops.