Computing shopping-list total using dictionaries [duplicate]

不羁岁月 提交于 2019-12-02 09:44:30

You can use list comprehensions ...

sum([ prices[s] for s in shopping_list ])

I'm assuming you want to compute the total cost of a list of items.

You've got a few issues with your existing code:

  • shopping_list is a dictionary, not a function or class (or "callable"). You can access items within it using shopping_list[key]
  • You're doing for item in foods but you're then assigning to item. This is probably not what you want.
  • key doesn't exist anywhere in your code except for prices[key]

I think you want something like this for your compute_bill function:

def compute_bill(food):
    total = 0
    for item in food:
         total += prices[item]
    return total

You can then call this using compute_bill(shopping_list). This function will now return 7.5 (which is the result you were looking for).

Your code and everyone else's here has ignored stock, so it can sell more items than are in stock; presumably that's a bug and you're supposed to enforce that restriction. There's two ways:

The iterative approach: for item in food:... check stock[item] is >0 , if yes add the price, decrement stock[item]. But you could simply sum each item-count and compute the min() with stock-count.

More Pythonic and shorter:

# Another test case which exercises quantities > stock
shopping_list = ["banana", "orange", "apple", "apple", "banana", "apple"]

from collections import Counter    
counted_list = Counter(shopping_list)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})

total = 0
for item, count in counted_list.items():
    total += min(count, stock[item]) * prices[item]

or as a one-liner:

sum( min(stock[item],count) * prices[item] for item,count in Counter(shopping_list).items() )

Your code looks weird, but this works:

def compute_bill(food):
    total = 0
    for item in food:
        total += prices[item]
    return total

shopping_list = ["banana", "orange", "apple"] print
compute_bill(shopping_list)

I'm assuming you want to use the prices dict to calculate prices for items in your shopping_list.

If you need any help, ask me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!