Created
March 1, 2013 21:34
-
-
Save rafalio/5067983 to your computer and use it in GitHub Desktop.
Coin Counting / Integer Partition
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
memo = dict() | |
# Returns a list of lists of all possibilities | |
def coin_count(amount,poss,curpos): | |
if amount == 0: | |
return [[]] | |
elif amount < 0 or curpos >= len(poss): | |
return [] | |
elif (amount,curpos) in memo: # memoized | |
return memo[(amount,curpos)] | |
# either use poss[0] | |
out = [] | |
for sublist in coin_count(amount-poss[curpos], poss, curpos): | |
out.append( [poss[curpos]] + sublist) | |
# or don't use it | |
out1 = coin_count(amount,poss,curpos+1) | |
# memoize | |
memo[(amount,curpos)] = out + out1 | |
return out + out1 | |
coins = [200,100,50,20,10,5,2,1] | |
print coin_count(200,coins,0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment