Skip to content

Instantly share code, notes, and snippets.

@signed0
Created April 18, 2013 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save signed0/5417065 to your computer and use it in GitHub Desktop.
Save signed0/5417065 to your computer and use it in GitHub Desktop.
from collections import defaultdict
from itertools import islice
def make_change(target, denominations):
"""Returns fewest coins needed to make up the target value
>>> make_change(100, [25, 10, 5, 1])
[(25, 4)]
>>> make_change(30, [25])
None
>>> make_change(50, [25, 10, 1])
[(10, 3)]
"""
def _explore_space(coins, target, smallest=0):
for i, coin in islice(enumerate(coins), smallest, None):
t = target - coin
if t < 0:
continue
elif t == 0:
yield [coin]
else:
for other_coins in _explore_space(coins, t, i):
other_coins.append(coin)
yield other_coins
denominations = sorted(denominations, reverse=True)
possibilities = list(_explore_space(denominations, target))
if len(possibilities) == 0:
return None
possibilities.sort(key=lambda x : len(x))
best_way = possibilities[0]
by_coin = defaultdict(int)
for coin in best_way:
by_coin[coin] += 1
return by_coin.items()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment