[Tutor] Finding the max value from a dictionary that does not exceed a variable's value.

Steven D'Aprano steve at pearwood.info
Sun Jan 31 00:01:22 EST 2016


On Sat, Jan 30, 2016 at 02:28:50PM +0000, Lawrence Lorenzo wrote:

> #The user enters a cost and then the amount of money given. You should 
> #write a program that works out what denominations of change should be 
> #given in pounds, 50p, 20p, 10p etc.#to do this the programme needs to 
> #divide the change ammount by 1.00 then 0.50 then 0.20 untill it 
> #reaches zero

I wouldn't use floating point numbers for this. I would take the cost 
in pounds and multiply by 100 to get the cost in pence, then divide by 
100, 50, 20, 10 etc to find out how many coins are needed.

To do this, you should use divmod:

py> divmod(47, 50)  # how many 50p in 47p?
(0, 47)
py> divmod(47, 20)  # how many 20p in 47p? any remainder?
(2, 7)
py> divmod(7, 10)
(0, 7)
py> divmod(7, 5)  # Does the UK have 5p coins?
(1, 2)


divmod(a, b) is the same as:

(a//b, a%b)

(how many b's in a, and any remainder?)


Also, I don't think that using a dict is useful or necessary in this 
case. Just use a list:

coins = [100, 50, 20, 10, 5, 2, 1]  # number of pence

and test the change against each coin in turn:

for coin in coins:
    if change//coin > 0:
        ...



-- 
Steve


More information about the Tutor mailing list