/
nikola.heat
/
PYAPI_Homework
Обзор
Документация
Войти
/
nikola.heat
/
PYAPI_Homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
main.py
101 строка
3 KB
Николай Копылов
Homework completed
15 июн 2026, 19:15
15 июн 2026, 19:15
8321a32
Код
Авторство
О чём код?
from pprint import pprint from pathlib import Path def read_cook_book(): cook_book = {} file_path = Path(__file__).parent / 'recipes.txt' with open(file_path, encoding='utf-8') as file: while True: dish_name = file.readline().strip() if not dish_name: break ingredients_count = int(file.readline().strip()) ingredients = [] for _ in range(ingredients_count): ingredient_name, quantity, measure = ( file.readline().strip().split(' | ') ) ingredients.append({ 'ingredient_name': ingredient_name, 'quantity': int(quantity), 'measure': measure }) cook_book[dish_name] = ingredients file.readline() return cook_book def get_shop_list_by_dishes(dishes, person_count): cook_book = read_cook_book() shop_list = {} for dish in dishes: if dish in cook_book: for ingredient in cook_book[dish]: name = ingredient['ingredient_name'] if name not in shop_list: shop_list[name] = { 'measure': ingredient['measure'], 'quantity': ingredient['quantity'] * person_count } else: shop_list[name]['quantity'] += ( ingredient['quantity'] * person_count ) return shop_list def merge_files(file_names, result_file='result.txt'): files_data = [] for file_name in file_names: file_path = Path(__file__).parent / file_name with open(file_path, encoding='utf-8') as file: lines = file.readlines() files_data.append({ 'name': file_name, 'count': len(lines), 'lines': lines }) files_data.sort(key=lambda x: x['count']) result_path = Path(__file__).parent / result_file with open(result_path, 'w', encoding='utf-8') as file: for item in files_data: file.write(item['name'] + '\n') file.write(str(item['count']) + '\n') file.writelines(item['lines']) file.write('\n') if __name__ == '__main__': cook_book = read_cook_book() pprint(cook_book) print() pprint( get_shop_list_by_dishes( ['Запеченный картофель', 'Омлет'], 2 ) ) merge_files(['1.txt', '2.txt', '3.txt'])