Ken Oliver wrote: > > -----Original Message----- >> From: Kent Johnson <[EMAIL PROTECTED]> >> Sent: Aug 6, 2007 3:46 PM >> To: Dick Moores <[EMAIL PROTECTED]> >> Cc: Python Tutor List <tutor@python.org> >> Subject: Re: [Tutor] Ingenious script (IMO) >> >> 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 > > Do you have a clever, pythonic way to suppress the denominations with "zero" > counts?
Sure, just use a list comprehension to filter the list of items: non_zero_items = [(k, v) for k, v in makechange(2218, denominations).items() if v!=0] print sorted(non_zero_items, reverse=True) Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor