问题
I tried calling the total of dictionary values for a shopping list made in list, but error has been coming up and summing to 10.5 instead of 7.5, it is supposed to give out the total price of items in a list, any list.
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
item = shopping_list(prices[key])
total += item
return total
shopping_list = ["banana", "orange", "apple"]
回答1:
You can use list comprehensions ...
sum([ prices[s] for s in shopping_list ])
回答2:
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 toitem
. This is probably not what you want. key
doesn't exist anywhere in your code except forprices[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).
回答3:
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() )
回答4:
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.
来源:https://stackoverflow.com/questions/29189978/computing-shopping-list-total-using-dictionaries