[Tutor] Ingenious script (IMO)

Eric Brunson brunson at brunson.com
Mon Aug 6 22:27:40 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?

Dictionary keys are not guaranteed to return in the order you add them.

You can sort them manually if it's important:

change = makechange( 2218, denominations )
print [ ( k, change[k] ) for k in sorted( change ) ]

Or, since you have a sorted list of denominations already:

change = makechange( 2218, denominations)
print [ ( k, change[k] ) for k in denominations ) ]

Or, if you know you're going to want them sorted use:

coins = []
for d in denominations:
       coins.append( ( d, int( amount/d ) )
       amount = amount%d

to get an ordered list of tuples.


Isn't programming fun?



>
> Dick
>
>
>
> ======================================
>                       Bagdad Weather
> <http://weather.yahoo.com/forecast/IZXX0008_f.html>



More information about the Tutor mailing list