/
saifadios
/
homework2
Обзор
Документация
Войти
/
saifadios
/
homework2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
Homework.py
77 строк
2 KB
Igor test
Добавлен .gitignore для .idea
02 июл 2025, 12:44
02 июл 2025, 12:44
18fcf3d
Код
Авторство
О чём код?
from pathlib import Path # ЗАДАЧА №1 --------------------------------------------------------- def read_cook_book(file_path: str | Path) -> dict: cook_book: dict[str, list[dict[str, str | int]]] = {} with open(file_path, encoding="utf-8") as fh: while True: dish_name = fh.readline().strip() if not dish_name: break ingredients_count = int(fh.readline()) ingredients: list[dict[str, str | int]] = [] for _ in range(ingredients_count): raw = fh.readline().strip() name, quantity, measure = (item.strip() for item in raw.split(" | ")) ingredients.append( { "ingredient_name": name, "quantity": int(quantity), "measure": measure, } ) cook_book[dish_name] = ingredients fh.readline() return cook_book # ЗАДАЧА №2 --------------------------------------------------------- def get_shop_list_by_dishes( dishes: list[str], person_count: int, cook_book: dict, ) -> dict: shop_list: dict[str, dict[str, int | str]] = {} for dish in dishes: if dish not in cook_book: raise ValueError(f"Блюда «{dish}» нет в книге рецептов") for item in cook_book[dish]: name = item["ingredient_name"] qty = item["quantity"] * person_count if name in shop_list: shop_list[name]["quantity"] += qty else: shop_list[name] = {"measure": item["measure"], "quantity": qty} return shop_list # ЗАДАЧА №3 --------------------------------------------------------- def merge_files_by_line_count( files: list[str | Path], result_file: str | Path = "result.txt", ) -> None: files_data: list[tuple[str, int, list[str]]] = [] for file in files: with open(file, encoding="utf-8") as fh: lines = fh.readlines() files_data.append((Path(file).name, len(lines), lines)) files_data.sort(key=lambda x: x[1]) with open(result_file, "w", encoding="utf-8") as out: for name, line_count, lines in files_data: out.write(f"{name}\n{line_count}\n") out.writelines(lines) out.write("\n")