Created
October 15, 2012 11:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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