首页 > codecademy中A Day at the Supermarket遇到问题

codecademy中A Day at the Supermarket遇到问题

1、题目

While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.
我理解的意思是:利用循环计算出food中所有物品的总价格,但是我们在求价格的时候,先判断在stock(库存)字典中对应的值是否大于0,如果是的话才进行求和并且把stock对应的value值减一,我的代码如下:

2、我的代码

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

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

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

print compute_bill(shopping_list)
print stock

我的代码运行后输出为:

5.5
{'orange': 31, 'pear': 15, 'banana': 5, 'apple': 0}

3、错误提示

Oops, try again. stock doesn't look quite right! Make sure to not call compute_bill since it changes the stock! It should contain: {'orange': 32, 'pear': 15, 'banana': 6, 'apple': 0}

4、我去网上查过,这个问题的解决方法是

def compute_bill(shopping_list):
    total=0
    for items in shopping_list:
        if stock[items] != 0: 
            total+= prices[items];
            stock[items] -= 1;
    return total

5、不理解的地方

我使用print进行函数调用,而正确做法直接传递了参数,这两种方式有什么本质上的不同?我不明白为什么会报出那个错误呢?


参考 http://stackoverflow.com/questions/23203606/codecademy-supermarket-subtract-error

删除 print compute_bill(shopping_list)这句好了

报错是叫你在自己的code里别调用compute_bill.估计是网站校验你答案的时候自己会做一些东西吧

【热门文章】
【热门文章】