/
kashnerok
/
PYAPI_Homework
Обзор
Документация
Войти
/
kashnerok
/
PYAPI_Homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.py
81 строка
2 KB
Kashnerok
Task2. Added shop_list
14 фев 2025, 19:28
14 фев 2025, 19:28
6382297
Код
Авторство
О чём код?
from pprint import pprint def read_file(file): '''Reading file to plain text''' with open(file, encoding="UTF-8") as f: content = f.read() return content def get_recipes(content:str): '''Get separate recipes from text''' return content.split('\n\n') def parse_ingredients(line:str): '''Parsing ingredients lines to dicts''' ingredient_name, quantity, measure = line.split(' | ') return { 'ingredient_name': ingredient_name.strip(), 'quantity': int(quantity), 'measure': measure.strip() } def create_cook_book(recipes:list): ''' Gets a dictionary from recipes.\n In the cycle, go through each recipe and get a separate\n name, quantity and list of ingredients. And writes down the\n ingredients in the dictionary. ''' cook_book = {} for recipe in recipes: lines = recipe.split('\n') dish_name = lines[0].strip() cnt_ingredients = int(lines[1]) ingredients = [] for i in range(cnt_ingredients): ingredients.append(parse_ingredients(lines[i + 2])) cook_book[dish_name] = ingredients return cook_book def get_shop_list_by_dishes(dishes, person_count): shop_list = {} for dish in dishes: if dish not in cook_book: # если блюда нет в рецептах, пропускаем его continue for ingr in cook_book[dish]: ingr_name = ingr['ingredient_name'] measure = ingr['measure'] quantity = ingr['quantity'] * person_count # если ингридиент ранее уже попал в словарь, # добавляем его количество if ingr_name in shop_list: shop_list[ingr_name]['quantity'] += quantity else: shop_list[ingr_name] = {'measure': measure, 'quantity': quantity} return shop_list if __name__== '__main__': file = "recipes.txt" text = read_file(file) recipes = get_recipes(text) cook_book = create_cook_book(recipes) # pprint(cook_book) pprint(get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2))