I am trying to define a function that returns a list of all combinations of legal coins that amount to a given sum. Let\'s say the given sum were 10 and the legal coins
You just need to turn your function into a generator, by replacing those print
calls with yield
.
I've also changed the default of used_coins
to None
, since you don't really want a default mutable argument here. See “Least Astonishment” and the Mutable Default Argument for details.
def count_change(tot_amount, coins, used_coins=None):
# Sort coins and get rid of coins that are too big
if used_coins is None:
used_coins = []
coins = [x for x in sorted(coins) if x <= tot_amount]
for coin in coins:
# If the first condition holds we have a valid combination
if tot_amount - sum(used_coins) == coin:
yield used_coins + [coin]
# Otherwise, if this coin is small enough, recurse to find combinations
# that use this coin in addition to the existing used_coins
elif tot_amount - sum(used_coins) > coin:
yield from count_change(tot_amount,
[x for x in coins if x <= coin],
used_coins + [coin])
for t in count_change(10, [5, 2, 3]):
print(t)
output
[2, 2, 2, 2, 2]
[3, 3, 2, 2]
[5, 3, 2]
[5, 5]
If you do actually need a list of the solutions, then simply run the generator into a list, like this:
seq = list(count_change(10, [5, 2, 3]))
print(seq)
output
[[2, 2, 2, 2, 2], [3, 3, 2, 2], [5, 3, 2], [5, 5]]