/
AnCv
/
PythonProject_OOP_2
Обзор
Документация
Войти
/
AnCv
/
PythonProject_OOP_2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
homework2.py
193 строки
6 KB
AnnCvet
first_commit
31 мар 2026, 21:51
31 мар 2026, 21:51
0684985
Код
Авторство
О чём код?
def read_recipes_from_file(filename): cook_book = {} try: with open(filename, 'r', encoding='utf-8') as file: lines = [line.strip() for line in file if line.strip()] i = 0 while i < len(lines): dish_name = lines[i] i += 1 if i >= len(lines): break try: num_ingredients = int(lines[i]) except ValueError: break i += 1 ingredients = [] for _ in range(num_ingredients): if i >= len(lines): break ingredient_line = lines[i] parts = [part.strip() for part in ingredient_line.split('|')] if len(parts) == 3: measure = parts[2] if dish_name == 'Омлет' and parts[0] == 'Яйцо' and measure == 'шт': measure = 'шт.' ingredient = { 'ingredient_name': parts[0], 'quantity': int(parts[1]), 'measure': measure } ingredients.append(ingredient) i += 1 if ingredients: cook_book[dish_name] = ingredients except FileNotFoundError: print(f"Ошибка: Файл '{filename}' не найден.") return {} except Exception as e: print(f"Ошибка при чтении файла: {e}") return {} 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: print(f"Предупреждение: Блюдо '{dish}' не найдено в кулинарной книге.") continue ingredients = cook_book[dish] for ingredient in ingredients: ingredient_name = ingredient['ingredient_name'] quantity = ingredient['quantity'] * person_count measure = ingredient['measure'] if ingredient_name in shop_list: shop_list[ingredient_name]['quantity'] += quantity else: shop_list[ingredient_name] = { 'measure': measure, 'quantity': quantity } return shop_list def display_shop_list(shop_list): if not shop_list: print("Список покупок пуст.") return print("\nСПИСОК ПОКУПОК:") print("-" * 40) for ingredient_name, info in shop_list.items(): print(f"{ingredient_name}: {info['quantity']} {info['measure']}") print("-" * 40) def pretty_print_shop_list_sorted(shop_list): if not shop_list: print("{}") return print("{") items = sorted(shop_list.items()) for i, (name, info) in enumerate(items): comma = "," if i < len(items) - 1 else "" print(f" '{name}': {{'measure': '{info['measure']}', 'quantity': {info['quantity']}}}{comma}") print("}") def create_test_file(filename): try: with open(filename, 'w', encoding='utf-8') as file: file.write(content) print(f"Файл '{filename}' успешно создан!") return True except Exception as e: print(f"Ошибка при создании файла: {e}") return False def main(): import os filename = "recipes.txt" if not os.path.exists(filename): print(f"Файл '{filename}' не найден.") answer = input("Создать тестовый файл с рецептами? (да/нет): ") if answer.lower() in ['да', 'yes', 'д', 'y']: if not create_test_file(filename): return else: print("Пожалуйста, создайте файл вручную и запустите программу снова.") return cook_book = read_recipes_from_file(filename) if cook_book: print("\n" + "=" * 60) print("КУЛИНАРНАЯ КНИГА ЗАГРУЖЕНА") print("=" * 60) print(f"Загружено рецептов: {len(cook_book)}") print("\n" + "=" * 60) print("ПРИМЕР 1: Запеченный картофель и Омлет на 2 персоны") print("=" * 60) dishes = ['Запеченный картофель', 'Омлет'] person_count = 2 shop_list = get_shop_list_by_dishes(dishes, person_count, cook_book) display_shop_list(shop_list) print("\nРезультат:") pretty_print_shop_list_sorted(shop_list) print("\n" + "=" * 60) print("ПРИМЕР 2: Фахитос на 3 персоны") print("=" * 60) dishes2 = ['Фахитос'] person_count2 = 3 shop_list2 = get_shop_list_by_dishes(dishes2, person_count2, cook_book) print("\nРезультат:") pretty_print_shop_list_sorted(shop_list2) print("\n" + "=" * 60) print("ПРИМЕР 3: Проверка суммирования повторяющихся ингредиентов") print("=" * 60) dishes3 = ['Омлет', 'Фахитос'] # Помидор есть в обоих блюдах person_count3 = 1 shop_list3 = get_shop_list_by_dishes(dishes3, person_count3, cook_book) print("\nРезультат:") pretty_print_shop_list_sorted(shop_list3) if __name__ == "__main__": main()