Python Forum
Need help with coin change program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with coin change program
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Need help with coin change program - by Gateux - Jun-24-2019, 01:20 PM
RE: Need help with coin change program - by perfringo - Jun-25-2019, 02:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Print the frequency of each coin for the combinations that sum to the amount N Pranav 3 2,605 May-19-2020, 06:16 AM
Last Post: Pranav
  Random module, coin flipping gus17 3 5,004 Jan-06-2020, 10:29 AM
Last Post: perfringo
  Adding and Removing coins to match Coin Bag Total infinite times Strayfe 8 4,712 Sep-11-2018, 07:30 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020