/
Pikeball59
/
PYAPI_Homework
Обзор
Документация
Войти
/
Pikeball59
/
PYAPI_Homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
main.py
103 строки
3 KB
Pikeball59
Initial commit: Рецепт блюд
11 июн 2025, 13:53
11 июн 2025, 13:53
362865f
Код
Авторство
О чём код?
def read_cook_book(file_path): cook_book = {} with open(file_path, 'r', encoding='utf-8') as f: lines = [line.strip() for line in f.readlines()] i = 0 while i < len(lines): if not lines[i]: i += 1 continue dish_name = lines[i] i += 1 ingredient_count = int(lines[i]) i += 1 ingredients = [] for _ in range(ingredient_count): if i >= len(lines): break parts = lines[i].split('|') if len(parts) != 3: i += 1 continue ingredient = { 'ingredient_name': parts[0].strip(), 'quantity': int(parts[1].strip()), 'measure': parts[2].strip() } ingredients.append(ingredient) i += 1 cook_book[dish_name] = ingredients return cook_book def get_shop_list_by_dishes(dishes, person_count, cook_book): shop_list = {} for dish in dishes: if dish not in cook_book: continue for ingredient in cook_book[dish]: name = ingredient['ingredient_name'] new_quantity = ingredient['quantity'] * person_count if name in shop_list: shop_list[name]['quantity'] += new_quantity else: shop_list[name] = { 'measure': ingredient['measure'], 'quantity': new_quantity } return shop_list def merge_files(files, output_file): file_data = [] for file_path in files: with open(file_path, 'r', encoding='utf-8') as f: content = f.readlines() file_data.append({ 'name': file_path, 'line_count': len(content), 'content': content }) file_data.sort(key=lambda x: x['line_count']) with open(output_file, 'w', encoding='utf-8') as f: for data in file_data: f.write(f"{data['name']}\n") f.write(f"{data['line_count']}\n") f.write(''.join(data['content'])) f.write('\n') if __name__ == "__main__": # Задача 1: Чтение cook_book cook_book = read_cook_book('recipes.txt') print("cook_book:") for dish, ingredients in cook_book.items(): print(f"{dish}:") for ing in ingredients: print(f" {ing}") print("\n") # Задача 2: Генерация списка покупок shop_list = get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2, cook_book) print("shop_list:") for ingredient, details in shop_list.items(): print(f"{ingredient}: {details}") print("\n") # Задача 3: Объединение файлов files_to_merge = ['files/1.txt', 'files/2.txt', 'files/3.txt'] merge_files(files_to_merge, 'result.txt') print("Файлы объединены в result.txt")