Reputation: 31
I have a problem with change-making algorithm. My code looks like this:
def algorithm():
denominations = [5, 2, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
numbers_of_denominations = [2, 1, 10, 10, 20, 10, 20, 50]
change = 9.39
i = 0
while(change > 0):
if(change >= denominations[i]):
number_of_coins = int((change / denominations[i]))
change = round(change - denominations[i] * number_of_coins, 2)
print(denominations[i], "x", number_of_coins)
i += 1
And it indeed gives me correct answer, but the problem is that what if I have limited number of coins? I don't know how to implement bounds for coins. for example if I would have:
How can I check if the number of coins are available? Current output is:
5$ x 1
2$ x 2
0.2$ x 1
0.1$ x 1
0.05$ x 1
0.02$ x 2
Which is incorrect because I have only 1 coin of 2$. I'm stuck.
Upvotes: 0
Views: 218
Reputation: 881513
Just make sure you don't use more than you have:
number_of_coins = min(numbers_of_denominations[i], int((change / denominations[i])))
This would give you min(1, 2)
for the $2 coins, which would only allow you to use the one that you have:
5 x 1
2 x 1
0.5 x 4
0.2 x 1
0.1 x 1
0.05 x 1
0.02 x 2
Just watch out if you don't have enough coins for the full amount, it'll probably result in an out of bounds error without further changes:
denominations = [5, 2, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
numbers_of_denominations = [2, 1, 10, 10, 20, 10, 20, 50]
change = 100
i = 0
while(change > 0):
# Check if we've run out of money.
if i >= len(denominations):
print("No change left, need", change)
break;
if(change >= denominations[i]):
number_of_coins = min(numbers_of_denominations[i], int((change / denominations[i])))
change = round(change - denominations[i] * number_of_coins, 2)
print(denominations[i], "x", number_of_coins)
i += 1
This shows:
5 x 2
2 x 1
0.5 x 10
0.2 x 10
0.1 x 20
0.05 x 10
0.02 x 20
0.01 x 50
No change left, need 77.6
Upvotes: 1