Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

import os import csv def open_file(): Function to open the input file file_name = input(Please enter the file name: ) if os.path.isfile(file_name): return file_name else:

import os

import csv

def open_file():

"""Function to open the input file"""

file_name = input("Please enter the file name: ")

if os.path.isfile(file_name):

return file_name

else:

print("File not found. Please try again.")

return open_file()

def build_dictionary(filename: os.PathLike):

recipes = {}

with open(filename, "r") as file:

reader = csv.DictReader(file)

for row in reader:

prep_time = int(row['prep_time'])

cook_time = int(row['cook_time'])

recipes[row['name']] = {

'ingredients': row['ingredients'].split(", "),

'diet': row['diet'],

'prep_time': prep_time,

'cook_time': cook_time,

'flavor_profile': row['flavor_profile'],

'course': row['course'],

'state': row['state'],

'region': row['region']

}

return recipes

def get_ingredients(recipes, food):

ingredients = set()

for name, recipe in recipes.items():

if name == food:

ingredients.update(recipe['ingredients'])

return ingredients

def get_useful_and_missing_ingredients(recipes, pantry):

useful_ingredients = set()

missing_ingredients = set()

for food in recipes:

food_ingredients = get_ingredients(recipes, food)

for ingredient in food_ingredients:

if ingredient in pantry:

useful_ingredients.add(ingredient)

else:

missing_ingredients.add(ingredient)

return useful_ingredients, missing_ingredients

def get_list_of_foods(recipes, ingredients):

foods = []

for recipe in recipes.values():

if all(ingredient in recipe['ingredients'] for ingredient in ingredients):

foods.append(recipe['name'])

return foods

def get_food_by_preference(recipes: dict, preference: str) -> list:

foods = []

for food, recipe in recipes.items():

if recipe['flavor_profile'] == preference:

foods.append(food)

return foods

def main():

print("Indian Foods & Ingredients. ")

file_name = open_file()

recipes = build_dictionary(file_name)

MENU = """

A. Input various foods and get the ingredients needed to make them!

B. Input various ingredients and get all the foods you can make with them!

C. Input various foods and ingredients and get the useful and missing ingredients!

D. Input various foods and preferences and get only the foods specified by your preference!

Q. Quit

: """

while True:

print(MENU)

choice = input("Enter your choice [A-D, Q]: ").upper()

if choice == "A":

food = input("Enter food name: ")

ingredients = get_ingredients(recipes, food)

print(f"Ingredients for {food}: {ingredients}")

elif choice == "B":

ingredients = input("Enter ingredients separated by commas: ").split(", ")

foods = get_list_of_foods(recipes, ingredients)

print(f"Foods that can be made with {ingredients}: {foods}")

elif choice == "C":

foods = input("Enter foods, separated by commas: ").split(", ")

pantry = input("Enter ingredients, separated by commas: ").split(", ")

useful_ingredients, missing_ingredients = get_useful_and_missing_ingredients(recipes, foods, pantry)

print(f"Useful ingredients: {useful_ingredients}")

print(f"Missing ingredients: {missing_ingredients}")

elif choice == "D":

preference = input("Enter your preferred flavor profile: ")

foods = get_food_by_preference(recipes, preference)

print(f"Foods with {preference} flavor profile: {foods}")

elif choice == "Q":

break

else:

print("Invalid choice. Try again.")

print("Thanks for Playing!")

if __name__ == "__main__":

main()

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

I am having the following problems with the code:

1) def get_useful_and_missing_ingredients() should have 3 parameters and should look something like this. Also following the guidelines below

get_useful_and_missing_ingredients(dict, list, list) tuple

This function takes 3 parameters: the dictionary from build_dictionary, a list of foods you want to make, and a list of ingredients that you currently have (in that order). The function returns a tuple of two lists: useful ingredients and missing ingredients. Given a list of foods and ingredients, the goal of this function is to find out which ingredients are useful and which are missing.

Useful ingredients are defined as follows: ingredients which you have (list of ingredients), and are also needed to make the list of foods (the set of ingredients for all the foods).

Missing ingredients are defined as follows: ingredients which you need to make the list of foods, but you currently do NOT have.

Return these as a tuple of two lists (the lists must be sorted in alphabetical order). Hint: use the previous function get_ingredients and call it within this function to make your life easier (set operations are very useful for this task! Also, when you call sorted() on a set, it returns a sorted list.

Here's an example:

foods = [Kalakand', 'Lassi'] ingredients_you_have = ['milk', 'sugar', 'ghee', 'rice', 'nuts'] get_useful_and_missing_ingredients(superD, foods, ingredients_you_have) Return (ingredients_you_have_and_need, ingredients_to_purchase) (['milk', 'nuts', 'sugar'], ['cottage cheese', 'yogurt'])

Refer to the .csv file to look at the ingredients and try to make sense of what is being asked of you for this function.

2) my for def get_ingredients() only find ingredients for one food, not multiple if given. For example:

get_ingredients(dict, list) set

This function takes in a list (of food names) and a dictionary (from build_dictionary), and returns a set of ingredients that are required to make all of the indicated foods. Find the foods in the dictionary and return the set of ingredients required to make them. Hint: Use the concepts of sets and their operations such as intersection and union to make this function. Return these ingredients as a set.

3) my def get_food_by_preference() only sorts by flavor profile when I want to sort it by a bunch of preferences. Also following the guidelines below

get_food_by_preference(dict, list) list

This function takes in the dictionary from build_dictionary and a list of preferences as parameters. It then returns a list of foods which match the conditions listed in the list of preferences sorted alphabetically. These conditions include region, state, diet (vegetarian or not vegetarian), and flavor. Hint: Use set addition and set differences to make your life easier. Sort the foods in alphabetical order and return them as a list.

Preferences are listed in the following order in the preferences parameter:

[Region, State, Diet (vegetarian status), Flavor]

Note, use None if there is no preference for a certain variable. For example, an example preference list could be as follows:

[None, None, 'non vegetarian', 'sweet']

The above list says that the user does not care what region or state (because both are None), but wants to filter out foods that are 'non vegetarian' and 'sweet' only.

4) my def get_list_of_foods() is giving me a Key error: 'name'. Also, it should follow the guidelines.

get_list_of_foods(dict, list) list

This function takes in a list of ingredients as a parameter and the dictionary from build_dictionary. It then returns a list of all possible foods that can be made given the ingredients. Iterate through every food in the dictionary and check to see if you have ALL the ingredients to make that food. If so, add it to your list of foods that you will return. Hint: Use set operations such as subsets and supersets to make your life easier. Return the food names as a list. Sort the foods in order of increasing total cooking time (remember total cooking time is prep time + cook time). Resolve any cooking-time ties by sorting the foods in alphabetical order (which should happen by default). Hints: (1) sort by cooking time then by name, (2) you can sum all element in a tuple by using the sum function, e.g. sum(tup))

5) I want to integrate the things below:

Use itemgetter() from the operator module to specify the key for sorting. For example, sorted(L,key=itemgetter(1,2)) return a sorted list on index 1 of the lists or tuple then sorted by index 2 to break ties.

The set class has 2 methods: .issuperset() and .issubset(). issuperset() returns True if a set has every elements of another set (passed as an argument). If not, it returns False. issubset() returns True if all items in the set exists in the specified set, otherwise it returns False.

6) Below is my .csv file and what it looks like before being run through my build_dictionary()

image text in transcribed

name, ingredients, diet, prep_time, cook_time, flavor_profile, course, state, region Balu shahi, "Maida flour, yogurt, oil, sugar", vegetarian,45,25, sweet, dessert, West Bengal, East Boondi, "Gram flour, ghee, sugar", vegetarian, 80, 30, sweet, dessert, Rajasthan, West Gajar ka halwa, "Carrots, milk, sugar, ghee, cashews, raisins", vegetarian, 15, 60, sweet, dessert, Punjab, North Ghevar, "Flour, ghee, kewra, milk, clarified butter, sugar, almonds, pistachio, saffron, green cardamom", vegetar Chikki, "Peanuts, jaggery", vegetarian, 10, 20, sweet, dessert, Maharashtra, West Dharwad pedha, "Milk, Sugar, Dharwadi buffalo milk", vegetarian, 20, 60, sweet, dessert, Karnataka, South Kajjikaya, "Rice flour, jaggery, coconut", vegetarian, 40, 15, sweet, dessert, Andhra Pradesh, South Anarsa, "Rice flour, jaggery, khus-khus seeds", vegetarian, 10, 50, sweet, dessert, Maharashtra, West Basundi, "Sugar, milk, nuts", vegetarian, 10, 35, sweet, dessert, Gujarat, West Lassi, "Yogurt, milk, nuts, sugar", vegetarian, 5, 5, sweet, dessert, Punjab, North Kheer, "Milk, rice, sugar, dried fruits", vegetarian, 10,40 , sweet, dessert, 1,1

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions