/
altes
/
Homework_files
Обзор
Документация
Войти
/
altes
/
Homework_files
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
main.py
136 строк
4 KB
Ne Neto no test
Tasks 1-3
22 май 2026, 23:41
22 май 2026, 23:41
193586a
Код
Авторство
О чём код?
import os def read_cook_book(file_path: str) -> dict: cook_book = {} with open(file_path, 'r', 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): line = file.readline().strip() ingredient_name, quantity, measure = line.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: list, person_count: int, cook_book: dict) -> dict: shop_list = {} for dish in dishes: # Если блюдо не найдено в книге, пропускаем его if dish not in cook_book: continue for ingredient in cook_book[dish]: name = ingredient['ingredient_name'] quantity = ingredient['quantity'] * person_count measure = ingredient['measure'] if name in shop_list: # Если ингредиент уже встречался, суммируем количество shop_list[name]['quantity'] += quantity else: shop_list[name] = { 'measure': measure, 'quantity': quantity } return dict(sorted(shop_list.items())) # Сортируем по алфавиту def print_cook_book_formatted(cook_book: dict) -> None: print("cook_book = {") items = list(cook_book.items()) for dish_idx, (dish, ingredients) in enumerate(items): print(f" '{dish}': [") for ing_idx, ing in enumerate(ingredients): line = ( f" {{'ingredient_name': '{ing['ingredient_name']}', " f"'quantity': {ing['quantity']}, " f"'measure': '{ing['measure']}'}}" ) if ing_idx < len(ingredients) - 1: line += "," print(line) if dish_idx < len(items) - 1: print(" ],") else: print(" ]") print(" }") def print_shop_list_formatted(shop_list: dict) -> None: print("shop_list = {") items = list(shop_list.items()) for idx, (name, data) in enumerate(items): comma = "," if idx < len(items) - 1 else "" print(f" '{name}': {{'measure': '{data['measure']}', 'quantity': {data['quantity']}}}{comma}") print("}") def merge_sorted_files(dir_path: str, output_file: str) -> None: files_data = [] for filename in os.listdir(dir_path): if filename.endswith('.txt'): filepath = os.path.join(dir_path, filename) with open(filepath, 'r', encoding='utf-8') as file: lines = file.readlines() while lines and lines[-1].strip() == '': lines.pop() if lines and not lines[-1].endswith('\n'): lines[-1] += '\n' content = ''.join(lines) files_data.append((filename, len(lines), content)) files_data.sort(key=lambda x: x[1]) with open(output_file, 'w', encoding='utf-8') as out: for filename, line_count, content in files_data: out.write(f"{filename}\n{line_count}\n{content}") if __name__ == '__main__': # Тестовый блок задания 1 cook_book = read_cook_book('recipes.txt') print_cook_book_formatted(cook_book) print("\n") # Тестовый блок задания 2 shop_list = get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2, cook_book) print_shop_list_formatted(shop_list) print("\n") # Тестовый блок задания 3 source_dir = 'text_files' result_file = 'result.txt' if os.path.isdir(source_dir): merge_sorted_files(source_dir, result_file) print(f"Файлы успешно объединены в '{result_file}'") print("Содержимое result.txt:") with open(result_file, 'r', encoding='utf-8') as f: print(f.read()) else: print(f"Папка '{source_dir}' не найдена.")