Apr-10-2020, 02:48 PM
I'm tearing my hair out trying to figure out what I'm doing wrong with access values in a dictionary!
Here's a greedy algorithm for returning change - with the change value set to 75.
Now I wanted to change this to print out "Fifty, Twenty, Five", so I changed the list to a dictionary. This is my broken code
Here's a greedy algorithm for returning change - with the change value set to 75.
def coin_change_greedy(n): coins = [50, 20, 10, 5, 1] i = 0 while(n>0): if(coins[i] > n): i = i+1 else: print(coins[i]) n = n-coins[i] print("\n") print('Coins in change') print(coin_change_greedy(75))Works nicely and prints out 50,20,5 as the answer.
Now I wanted to change this to print out "Fifty, Twenty, Five", so I changed the list to a dictionary. This is my broken code
def coin_change_greedy_2(n): coins = {'Fifty': 50,'Twenty': 20,'Ten': 10,'Five': 5,'One': 1} i = 0 while(n>0): if (coins[i] > n): i = i+1 else: print(coins.keys[i]) n = n-coins.values[i] print('Coins in change 2') print(coin_change_greedy_2(75))Unfortunately I can't figure out how to access the appropriate dict.key for the dict.value. In my head I thought coins.keys[0] would return 'Fifty', but I've got something wrong!! All help appreciated.