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):
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 quantitiesWhat 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: 2In 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: 0Maybe 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: 1I 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.
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.