Python Forum

Full Version: Need help with coin change program
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Write a program that reads an input representing a change which is an amount less than 1 dollar. The program calculates the change into 50, 10, 5 and 1 cent coins. The program then displays the number of each coin required for that change. E.g.
Enter change: 47
50 cent: 0
10 cent: 4
5 cent: 1
1 cent: 2

def main():
           print("This program calculates the change")
           amount = int(input("Enter the amount: "))
           half = amount // 50
           print("50 cent: ", half)
           dimes = amount // 10
           print("10 cent: ", dimes)
           nickels = amount // 5
           print("5 cent: ", nickels)
           pennies = amount // 1
           print("1 cent: ", pennies)
The output is way different from expected. Need some guidance on writing the correct calculations, thanks.

Output:
Enter the amount: 47 50 cent: 0 10 cent: 4 5 cent: 9 1 cent: 47
You need to subtract out each denomination before going on to the next one. In your example, after you give them 4 dimes, you only need to give them 7 cents more. But you try to give them 9 nickels (45 cents) because you haven't subtracted out the 40 cents from the 4 dimes.
It is always good idea to separate how from what. How to get coins quantity and what to do with these quantities.

How to get coins quantity? One needs to have quotient and reminder. There is function for that in Python: divmod(). Quotient is quantity of coins and reminder becomes new amount.

One can create function which iterates over coins values and assigns quantity to each coin value and returns dictionary (NB! dictionaries are insertion ordered from Python 3.6):

def coins(amount, coins=(50, 10, 5, 1)): 
    quantities = dict() 
    for coin in coins: 
        quantities[coin], amount = divmod(amount, coin) 
    return quantities 
What to do with coin quantities? Print out in any format you like? (below also requires 3.6 <= Python as f-strings are used):

>>> for k, v in coins(47).items(): 
...    print(f'{k} {"cents" if k > 1 else "cent"}: {v}') 
...
50 cents: 0
10 cents: 4
5 cents: 1
1 cent: 2
In Europe cents are in 50, 20, 10, 5, 2, 1 nomination. Function can be easily adjusted to reflect this:

>>> for k, v in coins(47, coins=(50, 20, 10, 5, 2, 1)).items(): 
...     print(f'{k} {"cents" if k > 1 else "cent"}: {v}') 
...                                                                       
50 cents: 0
20 cents: 2
10 cents: 0
5 cents: 1
2 cents: 1
1 cent: 0
Maybe print out only coins which have quantities:

>>> for k, v in coins(47, coins=(50, 20, 10, 5, 2, 1)).items(): 
...     if v: 
...         print(f'{k} {"cents" if k > 1 else "cent"}: {v}') 
...
20 cents: 2
5 cents: 1
2 cents: 1
I think that this way there is much more flexibility in what to do with result and how is somewhat abstracted away