我正在寻找一个解决方案,允许检查什么食谱,从一个给定的清单,我可以从我的冰箱里的原料。所以“食谱”和“冰箱”都是字典。
我所拥有的脚本不考虑值,而只考虑键。我想要找到一个解决方案,让我只能找到结果“沙拉”,因为这个脚本也将考虑到的价值(在食谱中的价值必须相等或低于冰箱的价值)。
    fridge = {
    "orange" : 5,
    "citron" : 3,
    "sel" : 100,
    "sucre" : 50,
    "farine" : 250,
    "lait" : 200,
    "oeufs" : 1,
    "tomates" : 6,
    "huile" : 100,
}
    
recipes = {
    "jus_de_fruit" : {
        "orange" : 3,
        "citron" : 1,
        "pomme" : 1
    },
    "salade" : {
        "tomates" : 4,
        "huile" : 10,
        "sel" : 3
    },
    "crepes" : {
        "lait" : 400,
        "farine" : 250,
        "oeufs" : 2
    }
}
def in_fridge(item):
    if item in dictionnaire_frigo:
        return True
    else:
        return False
def check_recipes(name):  
    for item in recipes[name]:
        item_in_fridge = in_fridge(item)
        if item_in_fridge == False:
            return False
    return True
for name in recipes:
    print(check_recipes(name))输出
假真
if check_recipes(name) == True: print(name)输出
沙拉和绉
但是我只想找到沙拉,因为我冰箱里没有足够的“烤面包”成分,而且不应该输出绉纸。
发布于 2022-04-18 16:47:42
使用您的输入字典fridge和recipes,这两种方法可以解决您的问题:
def in_fridge(ingredients: dict, fridge_food: dict) -> bool:
    
    for ingredient in ingredients:
        if ingredient not in fridge_food:
            return False
        if ingredients[ingredient] > fridge_food[ingredient]:
            return False
    return True
def check_recipes(recipes: dict, fridge_food: dict) -> None:
    for recipe in recipes:
        if in_fridge(recipes[recipe], fridge_food):
            print(f'There are enough ingredients to make {recipe}. ')把它们和你的字典一起使用
if __name__ == '__main__':
    check_recipes(recipes, fridge)产出:
There are enough ingredients to make salade. 如果您想要的话,让我们列出您可以做的食谱列表,然后使用:
def check_recipes(recipes: dict, fridge_food: dict) -> list:
    ans = []
    for recipe in recipes:
        if in_fridge(recipes[recipe], fridge_food):
            ans.append({recipe: recipes[recipe]})
    return ans那么输出是
[{'salade': {'tomates': 4, 'huile': 10, 'sel': 3}}]发布于 2022-04-18 16:32:53
你可以通过使用
fridge["orange"]  # Awnser : 5 还有你需要多少钱才能做绉纸
recipes["crepes"]["lait"]  # Awnser : 400使用这两个命令,您应该能够进行所需的比较。
发布于 2022-04-18 16:51:01
简单地迭代和比较(键首先找到匹配值,然后是值)。只要做:
for recipe, recipe_contents in recipes.items():
    if all(elem in list(fridge.keys()) for elem in list(recipes[recipe].keys())):
        if all(recipe_contents[elem] <= fridge[elem] for elem in recipe_contents):
            print(recipe)结果是:
saladehttps://stackoverflow.com/questions/71914372
复制相似问题