/
gregkhar
/
files-homework
Обзор
Документация
Войти
/
gregkhar
/
files-homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
CookBook
60 строк
2 KB
Barwolf
Completed homework
28 май 2026, 16:57
28 май 2026, 16:57
2d0590f
Код
Авторство
О чём код?
# Function for reading the content of a formatted .txt file with recipes def read_recipes_file(file): try: with open(file, 'r', encoding='utf=8') as f: recipes = f.read() print(recipes) except FileNotFoundError: print("Файл не найден.") except ValueError: print("Неверный формат") # Function for creating a cook book dictionary out of a formatted .txt file with recipes def create_cook_book(file): cook_book = {} dish_name = '' ingredient = {} try: with open(file, 'r', encoding='utf=8') as f: for line in f.readlines(): if line.strip() == '' or line.strip().isnumeric(): pass else: if '|' not in line: dish_name = line.strip() cook_book.update({dish_name:[]}) else: list = line.strip().split(' | ') ingredient = {'ingredient_name':list[0], 'quantity':list[1], 'measure':list[2]} cook_book[dish_name].append(ingredient) return cook_book except FileNotFoundError: print("Файл не найден.") except ValueError: print("Неверный формат") # Creating a cook book from the file cook_book = create_cook_book('recipes.txt') # Function for creating a shopping list based on the created cook book. Attributes: 1. a list of dish names 2. a number of persons def get_shop_list_by_dishes(dishes, person_count): shop_list = {} for dish in dishes: dish_ingredients = cook_book.get(dish) for i in dish_ingredients: ingredient_name = i.get('ingredient_name') if ingredient_name not in shop_list.keys(): parameters = {'measure':i.get('measure'), 'quantity':(int(i.get('quantity'))*person_count)} shop_list.setdefault(ingredient_name, parameters) else: new_quantity = shop_list.get(ingredient_name)['quantity']+(int(i.get('quantity'))*person_count) parameters = {'measure':i.get('measure'), 'quantity':new_quantity} shop_list.update({ingredient_name:parameters}) return shop_list # Creating a shop list based on the cook book shop_list = get_shop_list_by_dishes(['Омлет', 'Фахитос'], 2) print(read_recipes_file('recipes.txt'), '\n') print(cook_book, '\n') print(shop_list)