I am trying to learn how to write a program that can "make change".
It should take two numbers as input, one that is a monetary amount charged and the other that is a monetary amount given. It should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged. The values assigned to the bills and coins can be based on the monetary system of any current or former government. Try to design your program so that it returns as few bills and coins as possible.
Here is the code.
def make_change(given, charged, denominations = [100, 20, 10, 5, 2, 1, 0.25, 0.10, 0.05, 0.01]):
assert given >= charged, 'The customer has not given enough!'
change = {}
residual = given-charged
for denomination in denominations:
amount, residual = divmod(residual, denomination)
if amount:
change[denomination] = int(amount)
return change
print(make_change(1000, 575))
print(make_change(1000.84, 575))
{100: 4, 20: 1, 5: 1}
{100: 4, 20: 1, 5: 1, 0.25: 3, 0.05: 1, 0.01: 4}
I can't understand the if amount
statement, what does that mean?
In addition, the first output of divmod(425,100) is (4,25),and it returns change{100:4},the second output of divmod(425,20),it returns (21,5),so the result should be {100:4, 20:21}, however, the real result is {100: 4, 20: 1, 5: 1}. Can somebody help me, please?