Skip to content

Instantly share code, notes, and snippets.

@sumanvyj
Created October 15, 2012 11:00
Show Gist options
  • Select an option

  • Save sumanvyj/3891945 to your computer and use it in GitHub Desktop.

Select an option

Save sumanvyj/3891945 to your computer and use it in GitHub Desktop.
Uses dynamic programming to find the least number of coins needed to make change for some number of cents
coins = [1,5,10,25]
d = {} # stores tuples of the form (# of coins, [coin list])
# finds the minimum # of coins needed to
# make change for some number of cents
def m(cents):
if cents in d.keys():
return d[cents]
elif cents > 0:
choices = [(m(cents - x)[0] + 1, m(cents - x)[1] + [x]) for x in coins if cents >= x]
# given a list of tuples, python's min function
# uses the first element of each tuple for comparison
d[cents] = min(choices)
return d[cents]
else:
d[0] = (0, [])
return d[0]
for x in range(1, 100):
val = m(x)
print x, "cents requires", val[0], "coins:", val[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment