|
| 1 | +# Given an integer representing a given amount of change, write a |
| 2 | +# function to compute the total number of coins required to make |
| 3 | +# that amount of change. You can assume that there is always a |
| 4 | +# 1 coin |
| 5 | + |
| 6 | +from datetime import datetime |
| 7 | + |
| 8 | + |
| 9 | +def minCoinsRec(change, coins): |
| 10 | + if change == 0: |
| 11 | + return 0 |
| 12 | + tot_min_coins = 10000000 |
| 13 | + for coin in coins: |
| 14 | + if change-coin >= 0: |
| 15 | + this_min_coins = minCoinsRec(change-coin, coins) |
| 16 | + if this_min_coins < tot_min_coins: |
| 17 | + tot_min_coins = this_min_coins |
| 18 | + return tot_min_coins + 1 |
| 19 | + |
| 20 | + |
| 21 | +def minCoinsTopDownDP(change, coins, dp): |
| 22 | + if change == 0: |
| 23 | + return 0 |
| 24 | + if dp[change] != -1: |
| 25 | + return dp[change] |
| 26 | + tot_min_coins = 99999999 |
| 27 | + for coin in coins: |
| 28 | + if change-coin >= 0: |
| 29 | + this_min_coins = minCoinsTopDownDP(change - coin, coins, dp) |
| 30 | + if this_min_coins < tot_min_coins: |
| 31 | + tot_min_coins = this_min_coins |
| 32 | + dp[change] = tot_min_coins + 1 |
| 33 | + return dp[change] |
| 34 | + |
| 35 | + |
| 36 | +def minCoinsBottomUpDP(change, coins, dp): |
| 37 | + dp[0] = 0 |
| 38 | + for i in range(1, change+1): |
| 39 | + for coin in coins: |
| 40 | + if i-coin >= 0: |
| 41 | + curr_min_coins = dp[i-coin] + 1 |
| 42 | + if curr_min_coins < dp[i]: |
| 43 | + dp[i] = curr_min_coins |
| 44 | + return dp[change] |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == '__main__': |
| 48 | + coins = [1, 2, 5] |
| 49 | + change = 31 |
| 50 | + s = datetime.now() |
| 51 | + print "minimum coins with recursion: ", minCoinsRec(change, coins) |
| 52 | + e = datetime.now() |
| 53 | + print "total time taken using recursion: ", e-s |
| 54 | + |
| 55 | + dp = [-1] * (change+1) |
| 56 | + s = datetime.now() |
| 57 | + print "minimum coins with top down dp: ", minCoinsTopDownDP(change, coins, dp) |
| 58 | + e = datetime.now() |
| 59 | + print "total time taken using top down dp: ", e - s |
| 60 | + |
| 61 | + dp = [99999999] * (change+1) |
| 62 | + s = datetime.now() |
| 63 | + print "minimum coins with bottom up dp: ", minCoinsBottomUpDP(change, coins, dp) |
| 64 | + e = datetime.now() |
| 65 | + print "total time taken using bottom up dp: ", e - s |
0 commit comments