Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Created July 30, 2013 05:55
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/6110554 to your computer and use it in GitHub Desktop.
Save gigamonkey/6110554 to your computer and use it in GitHub Desktop.
It seems to me the time complexity of this is non-linear in the amount as you can see in the way the number of iterations required grows. Unless maybe I've messed something up in my translation from Clojure to Python.
#!/usr/bin/env python3
def count_ways_to_make_change(coins, total):
iterations = 0
ways = 0
digit = 0
counts = [0] * len(coins)
while digit < len(counts):
iterations += 1
counts[digit] += 1
new_sum = sum(d * c for d, c in zip(coins, counts))
if new_sum < total:
digit = 0
else:
if new_sum == total: ways += 1
counts[digit] = 0
digit += 1
return ways, iterations
if __name__ == '__main__':
coins = [ 1, 5, 10, 25 ]
for amount in [ 100, 200, 400, 800 ]:
ways, iterations = count_ways_to_make_change(coins, amount)
print('amount: {}; ways: {}; iterations: {}'.format(amount, ways, iterations))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment