""" Урок 41. Практикум 10 — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/41-practice-10/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-41.py """ # ==================================================================== # Пример 1. Counter: подсчёт, топ, арифметика # ==================================================================== from collections import Counter words = ["apple", "banana", "apple", "cherry", "banana", "apple"] counts = Counter(words) print(counts) # Counter({'apple': 3, 'banana': 2, 'cherry': 1}) print(counts.most_common(2)) # [('apple', 3), ('banana', 2)] print(counts["apple"]) # 3 print(counts["missing"]) # 0 — отсутствующий ключ не бросает KeyError more = Counter(["apple", "date"]) print(counts + more) # Counter({'apple': 4, 'banana': 2, 'cherry': 1, 'date': 1}) print(counts - more) # Counter({'apple': 2, 'banana': 2, 'cherry': 1}) print(list(counts.elements())[:5]) # ['apple', 'apple', 'apple', 'banana', 'banana'] # ==================================================================== # Пример 2. Задание 1 — популярные слова из нескольких текстов # ==================================================================== def popular_words(limit, *texts): words = [] for text in texts: words.extend(text.lower().replace(".", "").replace(",", "").split()) return Counter(words).most_common(limit) text1 = "This is a sample text with some repeated words." text2 = "Another sample text with different words." text3 = "Text processing is fun when words repeat." print(popular_words(5, text1, text2, text3)) # [('text', 3), ('words', 3), ('is', 2), ('sample', 2), ('with', 2)] # ==================================================================== # Пример 3. Задание 2 — defaultdict(list): группировка задач по категории # ==================================================================== from collections import defaultdict def group_tasks(tasks): result = defaultdict(list) for task, category in tasks.items(): result[category].append(task) return dict(result) tasks = {"task1": "работа", "task2": "учёба", "task3": "развлечения", "task4": "работа", "task5": "учёба"} grouped = group_tasks(tasks) print(grouped) # {'работа': ['task1', 'task4'], 'учёба': ['task2', 'task5'], 'развлечения': ['task3']} # ==================================================================== # Пример 4. Задание 3 — поиск задач по категории # ==================================================================== def find_tasks(tasks_by_category, category): return tasks_by_category.get(category, []) print(find_tasks(grouped, "учёба")) # ['task2', 'task5'] print(find_tasks(grouped, "спорт")) # [] — категории нет вовсе # ==================================================================== # Пример 5. Задание 5 — defaultdict(int): счётчик посещений страниц # ==================================================================== def count_visits(pages): counts = defaultdict(int) for page in pages: counts[page] += 1 return dict(counts) pages = ["home", "about", "home", "products", "home", "contact", "products"] print(count_visits(pages)) # {'home': 3, 'about': 1, 'products': 2, 'contact': 1} # ==================================================================== # Пример 6. Задание 6 — группировка слов по длине # ==================================================================== def group_by_length(words): groups = defaultdict(list) for word in words: groups[len(word)].append(word) return dict(groups) fruit_words = ["apple", "banana", "kiwi", "grape", "orange", "peach"] print(group_by_length(fruit_words)) # {5: ['apple', 'grape', 'peach'], 6: ['banana', 'orange'], 4: ['kiwi']} # ==================================================================== # Пример 7. Задание 4 — OrderedDict: очередь по приоритету # ==================================================================== from collections import OrderedDict def reorder_by_priority(tasks_dict): order = {"высокий": 0, "средний": 1, "низкий": 2} for key, _ in sorted(tasks_dict.items(), key=lambda item: order[item[1]]): tasks_dict.move_to_end(key) return tasks_dict tasks_od = OrderedDict({"task1": "низкий", "task2": "средний", "task3": "высокий", "task4": "низкий", "task5": "высокий"}) print(reorder_by_priority(tasks_od)) # OrderedDict([('task3', 'высокий'), ('task5', 'высокий'), ('task2', 'средний'), ('task1', 'низкий'), ('task4', 'низкий')]) print(list(tasks_od.keys())) # ['task3', 'task5', 'task2', 'task1', 'task4'] # ==================================================================== # Пример 8. Задание 7 — global и почему от него лучше уходить # ==================================================================== counter = 0 def increment_counter(): global counter counter += 1 increment_counter() increment_counter() print(f"Вызовов функции: {counter}") # Вызовов функции: 2 # ==================================================================== # Пример 9. Задание 8 — LRU-очередь на OrderedDict # ==================================================================== def update_lru_queue(tasks, new_tasks, max_size): queue = OrderedDict.fromkeys(tasks) for task in new_tasks: if task in queue: queue.move_to_end(task) else: queue[task] = None while len(queue) > max_size: queue.popitem(last=False) return list(queue) result = update_lru_queue( ["task1", "task2", "task3", "task4", "task5", "task6"], ["task4", "task1", "task7", "task2"], 4, ) print(result) # ['task4', 'task1', 'task7', 'task2'] # ==================================================================== # Пример 10. Когда всё же нужен именно OrderedDict, а не обычный dict # ==================================================================== d1 = {"a": 1, "b": 2} d2 = {"b": 2, "a": 1} print(d1 == d2) # True — обычный dict сравнивает только пары, порядок не важен od1 = OrderedDict({"a": 1, "b": 2}) od2 = OrderedDict({"b": 2, "a": 1}) print(od1 == od2) # False — OrderedDict учитывает порядок при сравнении print(list(d1.keys())) # ['a', 'b'] — порядок вставки сохранён и у обычного dict