下面是计算超市账单的代码。一切都很好,但问题是,有人告诉我,如果只有苹果的输入,这个解决方案就不会奏效。
我确实认为苹果的价值应该是0,因为苹果没有现货,但我仍然认为我做得不对。请帮帮忙。
groceries = ["apple","banana", "orange",]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(food):
total = 0
for item in food:
tot = prices[item] * stock[item]
print item, tot
total += tot
return total
computeBill(groceries)发布于 2012-10-17 09:33:38
我将自己回答这个问题并提出建议,因为您的computeBill功能的规范似乎没有很好地定义。
如果项目没有库存,并且您的讲师表示在这种情况下不能返回0,则您的其他选择是引发异常或指示错误状态的标记值。
def computeBill(food):
total = 0
for item in food:
stock_count = stock[item]
if stock_count == 0:
raise ValueError("item %s is out of stock" % item)
tot = prices[item] * stock_count
print item, tot
total += tot
return total或者,如果您不想引发异常,如果您觉得这无论如何都不是一个有效的总数,则可以返回-1:
if stock_count == 0:
return -1这个函数在计算列表和股票的方式上还有其他一些问题,但你说你现在不关心这些问题。
发布于 2012-10-17 09:33:38
我不知道为什么这样行不通。如果您的输入是['apple'],则会发生以下情况:
computeBill(['apple'])
total = 0
item = 'apple'
tot = price['apple'] * stock['apple']
tot = 2 * 0
print 'apple',0
total += 0
return total
return 0除非它们希望能够传入单个项而不将其包装在列表中,因此调用` `computeBill('apple')。在这种情况下,您必须在函数开始时进行类型检查。它可能看起来像这样
if type(food) is not list:
food = [food]发布于 2016-02-27 15:00:16
def compute_bill(food):
total=0
for item in food:
if stock[item]>0:
tot=prices[item]
total+=tot
stock[item]-=1
return total https://stackoverflow.com/questions/12925798
复制相似问题