Concerning Dictionaries and += in Python 2.x
Peter Otten
__peter__ at web.de
Wed Jan 21 03:43:31 EST 2015
Denis McMahon wrote:
> On Mon, 19 Jan 2015 16:12:57 -0800, Luke Tomaneng wrote:
>
>> I have been having a bit of trouble with the things mentioned in the
>> title.
>
> I've uploaded a slightly different approach to your code at:
>
> http://www.sined.co.uk/tmp/shop.py.txt
>
> def compute_bill(shopping):
> """
> Takes a dictionary of purchases requested in the form {item: quantity}
> Returns a tuple of:
> a dictionary of items supplied in the form {item: quantity}; and
> the cost of the supplied items
> """
> # the invoice amount
> invoice = 0
> # what we were able to supply
> sold = {k:0 for k in shopping.keys()}
There is also dict.from_keys()
> # check each requested item
> for item in shopping:
>
> # try and sell the requested qty
> for i in range(shopping[item]):
The inner loop is not just inefficient for stock sold in large quantities,
it will fail for stock sold by weight, volume etc.
> # if we have stock remaining
> if stock[item] > 0:
>
> # reduce stock count for item by 1
> stock[item] = stock[item] - 1
> # add 1 item to the sale
> sold[item] += 1
> # add item cost to the invoice
> invoice += prices[item]
>
> # return the items supplied and their cost
> return sold, invoice
Here is a possible alternative:
sold = {}
for item, wanted_quantity in shopping.iteritems(): # items() in Python 3
available_quantity = stock.get(item, 0)
sold_quantity = min(wanted_quantity, available_quantity)
sold[item] = sold_quantity
stock[item] -= sold_quantity
invoice += sold_quantity * prices[item]
More information about the Python-list
mailing list