如何实现Python函数找出配对食材的最高价值食谱组合?
Python食谱匹配函数修复
需求
开发一个Python函数,接收两个输入参数:
recipes:字典列表,每个字典代表一个食谱ingredients_collected:食材配对列表,每个元素是两个食材的组合
函数目标是返回匹配食谱的最高总价值以及完成的食谱数量。
匹配规则
- 每个食材配对仅可使用一次;
- 食谱的
ingredients_needed为必填食材列表,只要食材配对中的任一元素匹配某一项必填食材,即视为该必填食材已满足;完成所有必填食材的匹配后,可获得该食谱的item_value; - 若完成食谱的同时,有未使用的食材配对匹配到该食谱的
bonus_ingredient,需额外添加bonus_value到总价值中。
示例数据
食谱列表
recipes = [ {'player_name': 'Kei', 'recipe_name': 'Sushi (Fish)', 'ingredients_needed': 'rice, fish', 'item_value': 2, 'bonus_ingredient': '', 'bonus_value': ''}, {'player_name': 'Kei', 'recipe_name': 'Sushi (Veggie)', 'ingredients_needed': 'rice, veggie', 'item_value': 2, 'bonus_ingredient': '', 'bonus_value': ''}, {'player_name': 'Kei', 'recipe_name': 'Tempura (Veggie)', 'ingredients_needed': 'veggie', 'item_value': 2, 'bonus_ingredient': 'sauce', 'bonus_value': '1'}, {'player_name': 'Kei', 'recipe_name': 'Tempura (Fish)', 'ingredients_needed': 'fish', 'item_value': 2, 'bonus_ingredient': 'sauce', 'bonus_value': '1'}, {'player_name': 'Kei', 'recipe_name': 'Yakitori (Sub)', 'ingredients_needed': 'sub', 'item_value': 3, 'bonus_ingredient': 'sauce', 'bonus_value': '1'}, {'player_name': 'Kei', 'recipe_name': 'Yakitori (Protein)', 'ingredients_needed': 'protein', 'item_value': 3, 'bonus_ingredient': 'sauce', 'bonus_value': '1'}, {'player_name': 'Kei', 'recipe_name': 'Ramen (Protein)', 'ingredients_needed': 'pasta, veggie, protein', 'item_value': 4, 'bonus_ingredient': '', 'bonus_value': ''}, {'player_name': 'Kei', 'recipe_name': 'Ramen (Sub)', 'ingredients_needed': 'pasta, veggie, sub', 'item_value': 4, 'bonus_ingredient': '', 'bonus_value': ''} ]
收集到的食材配对
ingredients_collected = ['veggie, carrot', 'veggie, carrot', 'sub, seitan']
问题现状
当前实现的函数返回结果为 (5, 2, ['veggie', 'sub'], ['Ramen (Protein)', 'Ramen (Sub)']),但正确的预期返回值应为 (7, 3),需要修复函数逻辑以找到能获得最高价值的食谱组合。
内容的提问来源于stack exchange,提问作者bytebybyte
相关产品推荐
相关产品推荐

