[Tutor] Ingenious script (IMO)

Kent Johnson kent37 at tds.net
Mon Aug 6 21:46:45 CEST 2007


Dick Moores wrote:
> At 10:16 AM 8/6/2007, Eric Brunson wrote:
> 
> Your point about efficiency is well-taken.
> 
>> def makechange( amount, denominations ):
>>
>>     coins = {}
>>     for d in denominations:
>>         coins[d] = int( amount/d )
>>         amount = amount%d
>>
>>     return coins
> 
> OK, I used this this way:
> 
> ============================
> def makechange( amount, denominations ):
> 
>     coins = {}
>     for d in denominations:
>         coins[d] = int( amount/d )
>         amount = amount%d
> 
>     return coins
> 
> denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)
> amount = 2218
> print makechange(2218, denominations)
> ==================================
> 
> And get:
> {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0}
> 
> That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 
> bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters.
> 
> For amount = 3288:
> {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1}
> 
> Why those weird orders?

Dictionaries are not ordered. If you want to see it in order you could 
sort the list of key, value pairs:
print sorted(makechange(2218, denominations).items(), reverse=True)

Kent


More information about the Tutor mailing list