
求python大神解答关于dictionary的问题!!!><
已知一个dictionary"menu"的key是食物和价格.已知另一个dictionary"meal"的key是食物和每种食物点了几份。怎样可以写一个function,...
已知一个dictionary "menu" 的key是食物和价格. 已知另一个dictionary "meal" 的key是食物和每种食物点了几份。 怎样可以写一个function, 用这两个 dictionary arguments, "menu" and "meal", 然后 returns总价,再加上8.875% 的税和 25% 的小费。最后把最终的总价四舍五入到整数。这里是我写的:
menu = {"calamari":5, "carbonara":15, "branzino":15, "cheesecake":7.50}
meal = {"calamari":1, "carbonara":1, "branzino":1, "cheesecake":2}
food = 1*5 + 1*15 + 1*15 + 2*7.50 #evaluates to 50
tax = food*.08875 #evaluates to 4.4375
gratuity = (food + tax) * .25 #evaluates to 13.609375
total = food + tax + gratuity #evaluates to 68.046875
superman_iii_savings = math.floor(100*total)/100 #evaluates to 68.04**
total_cost = you_owe(menu, meal)
total_cost == 68.04 #evaluates to True
所以total_cost 是 68.04, 这个function的名字是 you_owe.
但是run module以后出现这个error:
Traceback (most recent call last):
File "C:\Users\xiaoshu\Desktop\check_please.template.py", line 25, in <module>
main()
File "C:\Users\xiaoshu\Desktop\check_please.template.py", line 20, in main
total_cost = you_owe(menu, meal)
TypeError: you_owe() takes 0 positional arguments but 2 were given
请问如何能让function在任何menu下都能运行?如果某种食物menu里没有,那它的价格就是$0.00. 展开
menu = {"calamari":5, "carbonara":15, "branzino":15, "cheesecake":7.50}
meal = {"calamari":1, "carbonara":1, "branzino":1, "cheesecake":2}
food = 1*5 + 1*15 + 1*15 + 2*7.50 #evaluates to 50
tax = food*.08875 #evaluates to 4.4375
gratuity = (food + tax) * .25 #evaluates to 13.609375
total = food + tax + gratuity #evaluates to 68.046875
superman_iii_savings = math.floor(100*total)/100 #evaluates to 68.04**
total_cost = you_owe(menu, meal)
total_cost == 68.04 #evaluates to True
所以total_cost 是 68.04, 这个function的名字是 you_owe.
但是run module以后出现这个error:
Traceback (most recent call last):
File "C:\Users\xiaoshu\Desktop\check_please.template.py", line 25, in <module>
main()
File "C:\Users\xiaoshu\Desktop\check_please.template.py", line 20, in main
total_cost = you_owe(menu, meal)
TypeError: you_owe() takes 0 positional arguments but 2 were given
请问如何能让function在任何menu下都能运行?如果某种食物menu里没有,那它的价格就是$0.00. 展开
1个回答
展开全部
你的you_owe函数在哪儿呢?error的意思是you_owe定义时不传入参数,而你调用的时候给了两个。
另外,是取整数还是保留后两位?
def you_owe(menu, meal):
# you can use the statement below to calculate food price instead.
# food = sum(menu[k] * v for (k, v) in meal.items() if k in menu)
food = 0
for (k, v) in meal.items():
if k in menu:
food += menu[k] * v
return int(food * 1.08875 * 1.25)
追问
哦!我懂了!!谢谢!!! 是保留后两位…我题目里说错了sorry……
那请问“如果某种食物menu里没有,那它的价格就是$0.00.”这个代码怎么写呢?
追答
保留后两位的话,return那里改成
return round(food*1.08875*1.25, 2)
就好了。
“如果menu里没有就是0”,只要
检验 k 是否在 D 中,如果在:计入账单;
否则:不计入(什么都不做)。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询