我有以下代码:
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)
练习告诉我按照这些说明完成功能:
我不知道该怎么做,我也不知道我的代码中是否有其他错误。
如果不清楚,库存中的值是该项目的库存,以及"价格中的值"是价格。
答案 0 :(得分:0)
首先,我没有看到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
答案 1 :(得分:0)
您可以执行以下操作
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:
这样吗。
答案 2 :(得分: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