-
Notifications
You must be signed in to change notification settings - Fork 173
E_Maksimova_lesson_08 #1272
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HelenMaksimova
wants to merge
1
commit into
DmitryChitalov:master
Choose a base branch
from
HelenMaksimova:E_Maksimova_lesson_08
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
E_Maksimova_lesson_08 #1272
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| """ | ||
| Задание 1. | ||
| Реализуйте кодирование строки "по Хаффману". | ||
| У вас два пути: | ||
| 1) тема идет тяжело? тогда вы можете, опираясь на пример с урока, сделать свою версию алгоритма | ||
| Разрешается и приветствуется изменение имен переменных, выбор других коллекций, различные изменения | ||
| и оптимизации. | ||
| КОПИПАСТ ПРИМЕРА ПРИНИМАТЬСЯ НЕ БУДЕТ! | ||
| 2) тема понятна? постарайтесь сделать свою реализацию. | ||
| Вы можете реализовать задачу, например, через ООП или предложить иной подход к решению. | ||
|
|
||
| ВНИМАНИЕ: примеры заданий будут размещены в последний день сдачи. | ||
| Но постарайтесь обойтись без них. | ||
| """ | ||
|
|
||
| # Реализация рассмотренного на уроке алгоритма через ООП | ||
|
|
||
|
|
||
| from collections import Counter | ||
| from collections import deque | ||
|
|
||
|
|
||
| # Вместо словарей будем использовать класс Tree (ничего лишнего, только узлы и потомки) | ||
| class Tree: | ||
|
|
||
| def __init__(self, root_obj): | ||
| self.root = root_obj | ||
| self.left_child = None | ||
| self.right_child = None | ||
|
|
||
|
|
||
| class HoffmanCode: | ||
|
|
||
| def __init__(self, string): | ||
| # строка, которую будем кодировать | ||
| self.string = string | ||
| # создаём отсортированную по частоте символов очередь из кортежей (символ, частота) | ||
| # приватный атрибут, внешний доступ к нему не нужен | ||
| self.__order = deque(sorted(Counter(string).items(), key=lambda x: x[1])) | ||
| # заполняем дерево (приватный метод, внешний доступ к нему не нужен) | ||
| self.__tree = self.__fill_tree() # приватный атрибут, внешний доступ к нему не нужен | ||
| # создаём и заполняем таблицу соответствия символов и кодов | ||
| self.code_table = dict() | ||
| self.__fill_code_table(self.__tree) # (приватный метод, внешний доступ к нему не нужен) | ||
|
|
||
| # получили экземпляр класса, где можно обратиться к кодируемой строке и таблице кодов | ||
|
|
||
| def __fill_tree(self): | ||
| # заполняем дерево по тому же принципу, что и в решении без ООП, но только вместо словарей | ||
| # будут объекты класса Tree и в итоге мы соберём один объект этого класса | ||
| while len(self.__order) > 1: | ||
| # берём два крайних левых элемента очереди | ||
| left = self.__order.popleft() | ||
| right = self.__order.popleft() | ||
| # и формируем из них дерево, у корня (узла) которого будет значение суммы частот элементов | ||
| node = Tree(left[1] + right[1]) | ||
| # и потомками будут элементы без их частот - деревья и символы | ||
| node.left_child = left[0] | ||
| node.right_child = right[0] | ||
| # выбираем, куда вставить дерево: | ||
| for idx, element in enumerate(self.__order): | ||
| if element[1] < node.root: | ||
| continue | ||
| else: | ||
| self.__order.insert(idx, (node, node.root)) | ||
| break | ||
| else: | ||
| self.__order.append((node, node.root)) # добавляем итоговый элемент | ||
| return self.__order[0][0] # возвращаем получившееся дерево | ||
|
|
||
| def __fill_code_table(self, tree, value=''): | ||
| # рекурсивно заполняем таблицу кодов по принципу: | ||
| # если аргумент tree - символ (строка), добавляем в словарь кодов эту строку и получившееся кодовое значение, | ||
| # если аргумент tree не символ (то есть дерево), берём его потомков и передаём их в функцию, | ||
| # а к передаваемому вместе с потомками кодовому значению добавляем 0 или 1 | ||
| if isinstance(tree, str): | ||
| self.code_table[tree] = value | ||
| return | ||
| self.__fill_code_table(tree.left_child, f'{value}0') | ||
| self.__fill_code_table(tree.right_child, f'{value}1') | ||
|
|
||
| def encode(self): | ||
| # формируем строку из кодов символов с помощью генератора | ||
| result = (self.code_table[letter] for letter in self.string) | ||
| return ' '.join(result) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
|
|
||
| str_1 = HoffmanCode('beep boop beer!') | ||
| str_2 = HoffmanCode('We are the champions, my friend!') | ||
|
|
||
| print(str_1.encode()) | ||
| for key, val in str_1.code_table.items(): | ||
| print(key, val) | ||
|
|
||
| print() | ||
|
|
||
| print(str_2.encode()) | ||
| for key, val in str_2.code_table.items(): | ||
| print(key, val) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """ | ||
| Задание 2.** | ||
|
|
||
| Доработайте пример структуры "дерево", | ||
| рассмотренный на уроке. | ||
|
|
||
| Предложите варианты доработки и оптимизации | ||
| (например, валидация значений узлов в соответствии с требованиями для бинарного дерева) | ||
|
|
||
| Поработайте с доработанной структурой, позапускайте на реальных данных. | ||
| """ | ||
|
|
||
|
|
||
| class BinaryTree: | ||
| def __init__(self, root_obj): | ||
| self.root = root_obj | ||
| self.left_child = None | ||
| self.right_child = None | ||
|
|
||
| def __str__(self): | ||
| # добавлено строкове представление | ||
| left = self.left_child.root if self.left_child is not None else None | ||
| right = self.right_child.root if self.right_child is not None else None | ||
| return f'<Узел {self.root}, дети: {left}, {right}>' | ||
|
|
||
| def insert_left(self, new_node): | ||
| # добавлена валидация нового узла по отношению к родительскому | ||
| if not self.validate(new_node): | ||
| if self.left_child is None: | ||
| self.left_child = BinaryTree(new_node) | ||
| else: | ||
| # добавлено автоматическое смещение прежнего узла в правого или левого потомка нового узла | ||
| tree_obj = BinaryTree(new_node) | ||
| if tree_obj.validate(self.left_child.root): | ||
| tree_obj.right_child = self.left_child | ||
| self.left_child = tree_obj | ||
| else: | ||
| tree_obj.left_child = self.left_child | ||
| self.left_child = tree_obj | ||
| else: | ||
| raise ValueError('Значение узла больше или равно корню!') | ||
|
|
||
| def insert_right(self, new_node): | ||
| # добавлена валидация нового узла по отношению к родительскому | ||
| if self.validate(new_node): | ||
| if self.right_child is None: | ||
| self.right_child = BinaryTree(new_node) | ||
| else: | ||
| # добавлено автоматическое смещение прежнего узла в правого или левого потомка нового узла | ||
| tree_obj = BinaryTree(new_node) | ||
| if tree_obj.validate(self.right_child.root): | ||
| tree_obj.right_child = self.right_child | ||
| self.right_child = tree_obj | ||
| else: | ||
| tree_obj.left_child = self.right_child | ||
| self.right_child = tree_obj | ||
| else: | ||
| raise ValueError('Значение нового узла меньше корня!') | ||
|
|
||
| def validate(self, value): | ||
| if value >= self.root: | ||
| return True | ||
| else: | ||
| return False | ||
|
|
||
| # метод просто возвращает значение атрибута, дублирование функционала, поэтому убрала | ||
| # def get_right_child(self): | ||
| # return self.right_child | ||
|
|
||
| # метод просто возвращает значение атрибута, дублирование функционала, поэтому убрала | ||
| # def get_left_child(self): | ||
| # return self.left_child | ||
|
|
||
| def set_root_val(self, obj): | ||
| self.root = obj | ||
|
|
||
| # метод просто возвращает значение атрибута, дублирование функционала, поэтому убрала | ||
| # def get_root_val(self): | ||
| # return self.root | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
|
|
||
| tree = BinaryTree(20) | ||
| tree.insert_left(19) | ||
| tree.insert_right(30) | ||
| print(tree.left_child) | ||
| print(tree.right_child) | ||
| tree.insert_left(15) | ||
| tree.insert_right(30) | ||
| print(tree.left_child) | ||
| print(tree.right_child) | ||
| print(tree.left_child.right_child) | ||
| print(tree.right_child.right_child) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. выполнено |
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
выполнено