[Tutor] Ingenious script (IMO)

Luke Paireepinart rabidpoobear at gmail.com
Mon Aug 6 22:32:00 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 implemented as hash tables, not linked lists or some 
other data structure.
see
> http://en.wikipedia.org/wiki/Hash_table
for more info.
a dictionary's keys may coincidentally be ordered how you'd expect them 
to be, but it's not required so you should never depend on that.
If you need them sorted, sort them :)
-Luke
>   



More information about the Tutor mailing list