Using python.
Trying to make a recipe program that tells me what meals(key) I can make based off of the current ingredients(list) that I have.
Here is my meal dictionary, the key is the meal and the value is the required ingredients:
breakfast = {
"cerealBowl" : ["milk", "cereal"],
"toast" : ["bread", "butter"],
"eggsBacon" : ["eggs", "bacon"],
"frenchToast" : ["bread", "eggs"]
}
And here is my list of ingredients that I currently have:
currentIngredients = ["milk", "bread", "rice", "butter", "eggs"]
I would like the program to return the meals(key) that I can make if all of the values are in my current ingredients list.
So far I have:
def scanRecipes():
for item in currentIngredients:
I'm not sure how to setup my next for loop/if statement to itterate over my breakfast dictionary values and compare the ingredients to my currentIngredients list.
Looking to get an output similar to:
"Meals available to make..." "toast" with ["bread", "butter"],"frenchToast" with ["bread", "eggs"]
CodePudding user response:
currentIngredients = set(["milk", "bread", "rice", "butter", "eggs"])
for key,ing in breakfast.items():
if currentIngredients.issuperset(set(ing)):
print( "You can make", key )
CodePudding user response:
Iterate over your recipes dict and filter to the recipes where you have all the ingredients:
breakfast_recipes = {
"cerealBowl" : ["milk", "cereal"],
"toast" : ["bread", "butter"],
"eggsBacon" : ["eggs", "bacon"],
"frenchToast" : ["bread", "eggs"]
}
def get_recipes(ingredients):
return {
r: i for r, i in breakfast_recipes.items()
if set(ingredients).issuperset(set(i))
}
current_ingredients = ["milk", "bread", "rice", "butter", "eggs"]
print("Meals available to make...")
for r, i in get_recipes(current_ingredients).items():
print(f"{r} with {i}")
Meals available to make...
toast with ['bread', 'butter']
frenchToast with ['bread', 'eggs']
CodePudding user response:
Available meals
You may for each meal in breakfast
look if the each required ingredient is in your currentIngredients
list:
available_meals = []
for meal, ingredients in breakfast.items():
available_ingrs = 0
for ingr in ingredients:
if ingr in currentIngredients:
available_ingrs = 1
if available_ingrs == len(ingredients): #if all required ingredients were met
available_meals.append((meal, ingredients))
Other answers are more elegant as they use the issuperset
method.
A is said to be a superset of B if A contains all elements of B.
In this case, currentIngredients
may be a superset of ingredients
if currentIngredients
contains all the elements of ingredients
:
set(currentIngredients).issuperset(ingredients) #returns a boolean
Note that the issuperset
function is a method of the set
type. That's why you have to convert currentIngredients
to a set
.
Printing an output
A simple printing program which iterates the available_meals
list:
def printMeals():
print("Meals available to make...")
for elem in available_meals:
print(repr(elem[0]), "with", elem[1])