Python编写的recipecal函数为什么仅返回第一个菜谱的卡路里计算结果?
问题原因
- 原
recipecal函数在遍历菜谱的循环内部直接执行了return calories语句,循环第一次运行计算完第一个菜谱的卡路里就直接终止函数返回结果,因此后续菜谱都不会被计算。 - 额外冗余问题:
rdict(recipes)和totalcal(data)在循环内被反复调用会重复执行相同计算,提前放在循环外执行一次即可提升运行效率。
修改方案
调整recipecal函数逻辑,用字典存储所有菜谱的计算结果,遍历完全部菜谱后再统一返回结果即可。
修改后的完整代码
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 def recipecal(recipes, data): # 提前计算公共数据,避免循环内重复调用 recipe_data = rdict(recipes) food_calorie = totalcal(data) # 存储所有菜谱的卡路里计算结果 result = {} for recipe_name in recipe_data: recipe_parts = recipe_data[recipe_name] calories = 0 for product in recipe_parts: number = recipe_parts[product] calories += number * food_calorie[product] result[recipe_name] = calories return result print(recipecal(["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10", "Green Salad1:Cabbage*10,Carrot*2,Pineapple*5", "T-Bone:Carrot*2,Steak Meat*1"] ,["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"]))
运行输出
修改后运行会返回所有菜谱的计算结果:
{'Pork Stew': 22295, 'Green Salad1': 597, 'T-Bone': 269}
内容的提问来源于stack exchange,提问作者Joshua Bradley
相关产品推荐
相关产品推荐

