无法用字典找出 Python 练习题

Can't figure out a Python exercise with dictionaries

我有以下代码:

shoppingList = ["banana","orange","apple"]

inventory = {"banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
    }

prices = {"banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
    }

def calculateBill(food):
    total = 0
    for k in food:
        total += prices[k]
    return total
calculateBill(shoppingList)

练习告诉我按照这些说明完成函数:

  1. 如果商品不在您的库存中,请不要在您的账单中添加该商品的价格。
  2. 购买一件商品后,从库存中减去一件。

我不知道该怎么做,也不知道我的代码中是否还有其他错误。

不清楚的话,inventory里面的值就是该商品的库存,"prices"里面的值就是价格。

首先,我没有看到 comida 在使用之前在任何地方定义。我假设 comida 是指 food.

这是一个简单的解决方案:

def calculateBill(food):
    total = 0
    for k in food:
        if inventory.get(k, 0) > 0:
            total += prices[k]                # updates total
            inventory[k] = inventory[k] - 1   # updates inventory
    return total

您可以执行以下操作

def calculateBill(food):
    total = 0
    for k in food:
        if k in inventory:
            if inventory[k] > 0:
                total += prices[k]
                inventory[k] = inventory[k] - 1
            else:
                print 'There are no %s in stock' % k
        else:
            print 'dont stock %s' % k
    return total

对于 1)

if k in inventory:

将检查密钥是否存在于您的库存字典中。

对于 2)

inventory[k] = inventory[k] - 1

将从您的库存中减去 1

此代码中的一个缺陷是它在允许购买之前不检查库存计数是否大于 0。所以

if inventory[k] > 0:

这样做。

这是一个完整的解决方案。

class Error(Exception):
    """Base class for Exceptions in this module"""
    pass

class QtyError(Error):
    """Errors related to the quantity of food products ordered"""
    pass

def calculateBill(food):

    def buy_item(food_item, qty=1, inv_dict=None, prices_dict=None):
        get_price = lambda item,price_dct: price_dct.get(item,9999999)
        if inv_dict is None:
            inv_dict = inventory
        if prices_dict is None:
            prices_dict = prices
        if inv_dict.get(food_item, 0) >= qty:
            inv_dict[food_item] -= qty
            return sum(get_price(food_item, prices_dict) for _ in range(qty))
        else:
            raise QtyError("Cannot purchase item '{0}' of quantity {1}, inventory only contains {2} of '{0}'".format(food_item, qty, inv_dict.get(food_item,0)))

    total = sum(buy_item(food_item, 1, inventory, prices) for food_item in food)
    return total