计算超级m的帐单

2024-06-01 18:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是计算超级市场账单的代码。一切都很好,但问题是,我被告知,如果输入只有苹果,这个解决方案就行不通。

我相信苹果的价值应该是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)

Tags: 苹果applefoodstockitemtotalbananaprices
3条回答

我不知道为什么这样不行。如果您的输入是['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]

我将自己给出这个答案并提出建议,因为您的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

这个函数还有一些其他的问题,比如它是如何计算列表和股票的,但是你说你现在不关心这些问题。

def compute_bill(food):
  total=0
  for item in food:
    if stock[item]>0:
      tot=prices[item]
      total+=tot
      stock[item]-=1
  return total  

相关问题 更多 >