I am trying to implement a simple Dynamic Programming function that, given a list of coins types and an integer amount, calculates the minimum number of coins required to make a given amount. e.g. coins = [1,2,5]; amount = 11 gives output of 3 for the possibility of 5 + 5 + 1 coin types.
Implemented the following code (output -1 if no match found):
def coinChange(coins, amount, dp = {}): if amount in dp: print('from mem',dp) return dp[amount] dp[0] = 0 for c in coins: dp[c] = 1 chk = [(amount - i) for i in coins if (amount-i) > 0] out = list(map(lambda x:coinChange(coins,x,dp),chk)) out2 = [i for i in out if i >= 0] print(amount,chk,out,out2,dp) if out2: dp[amount] = 1 + min(out2) else: dp[amount] = -1 return dp[amount] When calling this function, the first call gives the expected full run of the code. However, subsequent calls refer to the original dp variable of the function and returns values from that.
I understand that this variable dp should have gone out of memory after the function quits. Please help in understanding.
Input: ''' c = [1,2,5] a = 11 coinChange(c,a) '''
First call: Normal output for all recursive calls
Second Call output: from memory {0: 0, 1: 1, 2: 1, 5: 1, 3: 2, 4: 2, 6: 2, 7: 2, 8: 3, 9: 3, 10: 2, 11: 3} 3
https://stackoverflow.com/questions/66828501/python-function-not-clearing-dict-variable-from-memory March 27, 2021 at 02:08PM
没有评论:
发表评论