Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Last active December 20, 2015 09:49
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 gigamonkey/6110819 to your computer and use it in GitHub Desktop.
Save gigamonkey/6110819 to your computer and use it in GitHub Desktop.
A somewhat low-level implementation of the constant space, linear time change counting algorithm. (By low-level, I mean something that could be straightforwardly translated to C if I actually knew C.)
#!/usr/bin/env python3
def ways(amount, coins):
size = sum(coins) + len(coins)
starts = [ i + sum(coins[:i]) for i in range(len(coins)) ]
data = [ i in starts for i in range(size) ]
for offset in range(1, amount + 1):
prev = 0
for s, c in zip(starts, coins):
prev = data[(s-offset) % size] = prev + data[(s+c-offset) % size]
# And there's the answer. Ta Da!
return data[(starts[-1] - amount) % size]
if __name__ == '__main__':
from sys import argv
amount = int(argv[1])
coins = [ int(x) for x in argv[2:] ]
print(ways(amount, coins))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment