/
Vrenny
/
Task_2
Обзор
Документация
Войти
/
Vrenny
/
Task_2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Task_2.py
81 строка
3 KB
Vren
Update homework
24 янв 2026, 09:55
24 янв 2026, 09:55
c820a2a
Код
Авторство
О чём код?
open(file=r'recipes.txt', mode='r') def read_cookbook(path_to_file): cook_book = {} with open(path_to_file, mode='r', encoding='utf-8') as file: while True: dish = file.readline().strip() # первая строка if not dish: break count = int(file.readline().strip()) #вторая строка ingredients = [] #список словарей с описаниен ингридиентов for ing in range(count): #цикл считывает столько строк, сколько указано в переменной count и все добавляет в список line = file.readline().strip() ing_name, quantity, measure = line.split(' | ') ingredients.append({'ingredient': ing_name, 'quantity': int(quantity), 'measure': measure}) cook_book[dish] = ingredients file.readline() return cook_book book = read_cookbook(r'recipes.txt') # функция к заданию 1 # print(book) def calc_ingredients(dishes, person): book = read_cookbook(r'recipes.txt') dish_ing_list = {} for dish in dishes: set_ing = book[dish] # получаем список ингридиентов (список словарей) # print(set_ing) for ing in set_ing: n = ing['ingredient'] m = ing['measure'] q = ing['quantity'] * person # print(ing) if n in dish_ing_list: dish_ing_list[n]['quantity'] += q else: dish_ing_list[n] = {'measure': m, 'quantity': q} # print(dish_ing_list) return dish_ing_list calc_ingredients(['Запеченный картофель', 'Омлет'], 2) # функция к заданию 2 def sort_file (file_list): numb_line = {} for file in file_list: with open(file, 'r', encoding='utf-8') as file_o: lines = file_o.readlines() count = len(lines) numb_line[file] = count sorted_keys = sorted(numb_line, key=numb_line.get) print(sorted_keys) # for key in sorted_keys: # with open(key, 'r', encoding='utf-8') as src: # content = src.read() # with open('destination.txt', 'w', encoding='utf-8') as dst: # dst.write(key + '\n') # dst.write(str(numb_line[key]) + '\n') # dst.write(content + '\n') with open('destination.txt', 'w', encoding='utf-8') as dst: for key in sorted_keys: with open(key, 'r', encoding='utf-8') as src: content = src.read() dst.write(key + '\n') dst.write(str(numb_line[key]) + '\n') dst.write(content + '\n') sort_file([r'1.txt', r'2.txt', r'3.txt']) # функция к заданию 3