Created
December 28, 2016 19:25
-
-
Save drem-darios/9e5d74f4507c91655bd2c86015eeb1ec to your computer and use it in GitHub Desktop.
Coin change problem using dynamic programming
This file contains 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
def get_change(coin_values, total, coin_count, used_coins): | |
for cents in range(total+1): | |
count = cents | |
coin = 1 | |
for coin_value in coin_values: | |
if coin_value <= cents: # Could use a lambda here | |
if coin_count[cents-coin_value] + 1 < count: | |
count = coin_count[cents-coin_value] + 1 | |
coin = coin_value | |
coin_count[cents] = count | |
used_coins[cents] = coin | |
return coin_count[total] | |
def get_used_coins(coins, total): | |
result = [] | |
coin = total | |
while coin > 0: | |
used_coin = coins[coin] | |
result.append(used_coin) | |
coin = coin - used_coin # Backtrack | |
return result | |
def main(): | |
total = 72 | |
coin_values = [1,5,10,21,25] | |
coin_count = [0]*(total+1) | |
used_coins = [0]*(total+1) | |
print("Minimum coins required: " + str(get_change(coin_values, total, coin_count, used_coins))) | |
print("Coins used: " + str(get_used_coins(used_coins, total))) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment