我正在寻找一种解决方案,允许检查从给定列表中我可以从我冰箱里的成分制作的食谱。所以这两个"食谱"one_answers";fridge"是字典。
我的脚本不考虑值,而只考虑键。我想找到一个解决方案,让我只找到结果"沙拉"。因为这个脚本还会考虑值(recipes中的值必须等于或低于fridge中的值)。
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))
输出false true true
if check_recipes(name) == True: print(name)
输出沙拉和可丽饼
但我只想找到沙拉,因为我没有足够的配料"酱油"在我的冰箱里,它不应该输出crepe
使用您的输入字典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}}]
你可以使用
查看你有多少橙子fridge["orange"] # Awnser : 5
和用
做薄饼需要多少钱recipes["crepes"]["lait"] # Awnser : 400
使用这两个命令,您应该能够进行您想要的比较。
简单地迭代和比较(键先找到匹配,然后是值)。只做:
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)
结果是:
salade
collections.Counter
根据您想要的确切逻辑实现比较,因此您可以通过为冰箱内容和每个配方创建Counter
s并进行比较来使其非常简单:
>>> from collections import Counter
>>> for n, recipe in recipes.items():
... if Counter(recipe) <= Counter(fridge):
... print(n)
...
salade
如果出于某种原因你需要在没有Counter
的情况下实现它,那么迭代recipe
中的项目并将每个项目与冰箱中的数量进行比较是非常简单的(这与Counter(recipe) <= Counter(fridge)
在幕后所做的事情完全相同):
>>> for n, recipe in recipes.items():
... if all(c <= fridge.get(i, 0) for i, c in recipe.items()):
... print(n)
...
salade
def in_fridge(item):
return item[0] in fridge.keys() and item[1] <= fridge[item[0]]
def check_recipes(name):
for item in recipes[name].items():
if not in_fridge(item):
return False
return True
for name in recipes.keys():
print(check_recipes(name))
False
True
False