如何编写Python mealcal函数 调用辅助函数返回正确的餐食热量计算结果
mealcal函数正确实现方案
你已经编写的totalcal和rdict两个辅助函数逻辑完全正确,我们可以直接复用,不需要额外修改。以下是逻辑最简单、最容易理解的实现方案:
实现思路
- 提前调用
totalcal(data)得到所有食材每单位的热量字典,避免重复计算 - 提前调用
rdict(recipes)得到所有菜谱的结构化字典,结构为{菜名: {食材名: 所需数量}} - 逐一遍历
menu里的每道菜,匹配菜谱后把每样食材的用量乘对应热量求和,就是当前菜的总热量 - 把所有菜的热量收集成列表返回即可
完整代码
# 原有正确辅助函数,无需修改 def totalcal(data): calorie_dict = {} for el in data: food, values = el.split(':') a, b, c = values.split(',') calories = (int(a) * 5) + (int(b) * 5) + (int(c) * 9) calorie_dict[food] = calories return calorie_dict def rdict(recipes): recipes_splitted = {} for r in recipes: recipe_name, parts = r.split(":") recipe_parts = {} for part in parts.split(','): product, number = part.split('*') recipe_parts[product] = int(number) recipes_splitted[recipe_name] = recipe_parts return recipes_splitted # 新的mealcal实现,逻辑清晰易懂 def mealcal(menu, recipes, data): # 提前计算好固定的食材热量和菜谱结构,不用重复运行 food_calorie = totalcal(data) all_recipes = rdict(recipes) result = [] # 逐道菜计算总热量 for dish in menu: # 拿到当前菜需要的食材和对应用量 ingredients = all_recipes[dish] dish_total = 0 for ingre, count in ingredients.items(): dish_total += count * food_calorie[ingre] result.append(dish_total) return result
测试验证
# 测试参数 menu = ["Pork Stew", "Green Salad1", "T-Bone"] recipes = ["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10", "Green Salad1:Cabbage*10,Carrot*2,Pineapple*5", "T-Bone:Carrot*2,Steak Meat*1"] data = ["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5", "Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"] print(mealcal(menu, recipes, data)) # 输出结果:[22295, 690, 405],和需求完全匹配
如果你原来的
menu确实是["T-Bone", "T-Bone", "Green Salad1"],输出结果会是[405, 405, 690],只需要调整menu的顺序即可得到你想要的目标结果。
内容的提问来源于stack exchange,提问作者Joshua Bradley
相关产品推荐
相关产品推荐

