From 323c3e4c2c68d8431c9d52c0031243786b9be20c Mon Sep 17 00:00:00 2001 From: Barrakuda Date: Sat, 5 Jun 2021 16:46:57 +0200 Subject: [PATCH 1/2] initial commit --- .idea/misc.xml | 4 + .../shelved.patch | 86 ++++++++ .../shelved.patch | 0 ..._16_05_2021_14_08__Default_Changelist_.xml | 4 + .idea/vcs.xml | 6 + .idea/workspace.xml | 203 ++++++++++++++++++ task1.py | 10 + task2.py | 76 +++++++ 8 files changed, 389 insertions(+) create mode 100644 .idea/misc.xml create mode 100644 .idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]/shelved.patch create mode 100644 .idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]1/shelved.patch create mode 100644 .idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08__Default_Changelist_.xml create mode 100644 .idea/vcs.xml create mode 100644 .idea/workspace.xml create mode 100644 task1.py create mode 100644 task2.py diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..81dd32a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]/shelved.patch b/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]/shelved.patch new file mode 100644 index 0000000..123421d --- /dev/null +++ b/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]/shelved.patch @@ -0,0 +1,86 @@ +Index: .idea/workspace.xml +IDEA additional info: +Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP +<+>\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n + + +- ++ + ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ + ++ ++ ++ 1621166253676 ++ ++ ++ 1621166429685 ++ ++ + ++ + ++ ++ ++ ++ ++ ++ ++ ++ ++ + +\ No newline at end of file diff --git a/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]1/shelved.patch b/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08_[Default_Changelist]1/shelved.patch new file mode 100644 index 0000000..e69de29 diff --git a/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08__Default_Changelist_.xml b/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08__Default_Changelist_.xml new file mode 100644 index 0000000..659cbc6 --- /dev/null +++ b/.idea/shelf/Uncommitted_changes_before_Checkout_at_16_05_2021_14_08__Default_Changelist_.xml @@ -0,0 +1,4 @@ + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..96f1a66 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,203 @@ + + + + + + + + + + + + + + + + + + + - + + + + + + - + + - + - - - + + + + - + + + - - 1622388060994 + + 1620734349569 - 1622411178691 + 1621080037672 - - 1622411237391 - - @@ -163,41 +206,53 @@ - + + + + + + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - + \ No newline at end of file diff --git a/task1.py b/task1.py index 72f45e3..23ca3f6 100644 --- a/task1.py +++ b/task1.py @@ -7,4 +7,81 @@ и оптимизации. 2) тема понятна? постарайтесь сделать свою реализацию. Вы можете реализовать задачу, например, через ООП или предложить иной подход к решению. -""" \ No newline at end of file +""" + +# Реализовано через ООП + + +from collections import Counter + + +class Node: + + def __init__(self, left, right): + self.left = left + self.right = right + self.frequency = self.left.frequency + self.right.frequency + + +class Symbol: + + def __init__(self, symbol, frequency): + self.symbol = symbol + self.frequency = frequency + self.code = '' + + def __str__(self): + return self.symbol + + +class Phrase: + + def __init__(self, phrase): + self.tree = [] + self.symbols = {} + self.frequency_count(phrase) + self.create_tree() + self.symbols_code(self.tree) + self.code = self.phrase_code(phrase) + + def frequency_count(self, phrase): + count_dict = Counter(phrase) + for i in count_dict: + symbol = Symbol(i, count_dict[i]) + self.tree.append(symbol) + self.symbols[i] = symbol + self.tree.sort(key=lambda k: f'{k.frequency}') + + def frequency_sort(self, node): + self.tree.insert(0, node) + for i in range(len(self.tree) - 1): + if self.tree[i].frequency > self.tree[i + 1].frequency: + self.tree[i], self.tree[i + 1] = self.tree[i + 1], self.tree[i] + else: + break + + def create_tree(self): + while len(self.tree) > 1: + node = Node(self.tree[0], self.tree[1]) + self.tree = self.tree[2:] + self.frequency_sort(node) + self.tree = self.tree[0] + + def symbols_code(self, tree, code=''): + if isinstance(tree, Symbol): + tree.code = code + else: + self.symbols_code(tree.left, code + '0') + self.symbols_code(tree.right, code + '1') + + def phrase_code(self, phrase): + code = '' + for i in phrase: + code += ' ' + self.symbols[i].code + return code + + def __str__(self): + return self.code + + +print(Phrase(input('Введите текст: '))) diff --git a/task2.py b/task2.py index 6423b17..6521eaa 100644 --- a/task2.py +++ b/task2.py @@ -7,6 +7,11 @@ Поработайте с доработанной структурой, позапускайте на реальных данных - на клиентском коде. """ +# Добавлена валидация значений левого и правого потомка для корня дерева. Я ещё думал как бы сделать валидацию для +# всех последующих потомков, но для этого надо переписать половину скрипта, если не весь, и к тому же потом я посмотрел +# пример и в нём этого нет, так что оставил валидацию только для правого и левого потомков корня. + + class BinaryTree: def __init__(self, root_obj): # корень @@ -18,59 +23,74 @@ def __init__(self, root_obj): # добавить левого потомка def insert_left(self, new_node): - # если у узла нет левого потомка - if self.left_child == None: - # тогда узел просто вставляется в дерево - # формируется новое поддерево - self.left_child = BinaryTree(new_node) - # если у узла есть левый потомок + if new_node < self.get_root_val(): + # если у узла нет левого потомка + if self.left_child is None: + # тогда узел просто вставляется в дерево + # формируется новое поддерево + self.left_child = BinaryTree(new_node) + # если у узла есть левый потомок + else: + # тогда вставляем новый узел + tree_obj = BinaryTree(new_node) + # и спускаем имеющегося потомка на один уровень ниже + tree_obj.left_child = self.left_child + self.left_child = tree_obj else: - # тогда вставляем новый узел - tree_obj = BinaryTree(new_node) - # и спускаем имеющегося потомка на один уровень ниже - tree_obj.left_child = self.left_child - self.left_child = tree_obj + print("Impossible. Too big") # добавить правого потомка def insert_right(self, new_node): - # если у узла нет правого потомка - if self.right_child == None: - # тогда узел просто вставляется в дерево - # формируется новое поддерево - self.right_child = BinaryTree(new_node) - # если у узла есть правый потомок + if new_node > self.get_root_val(): + # если у узла нет правого потомка + if self.right_child is None: + # тогда узел просто вставляется в дерево + # формируется новое поддерево + self.right_child = BinaryTree(new_node) + # если у узла есть правый потомок + else: + # тогда вставляем новый узел + tree_obj = BinaryTree(new_node) + # и спускаем имеющегося потомка на один уровень ниже + tree_obj.right_child = self.right_child + self.right_child = tree_obj else: - # тогда вставляем новый узел - tree_obj = BinaryTree(new_node) - # и спускаем имеющегося потомка на один уровень ниже - tree_obj.right_child = self.right_child - self.right_child = tree_obj + print("Impossible. Too small") # метод доступа к правому потомку def get_right_child(self): - return self.right_child + if self.right_child: + return self.right_child + else: + print('Нет правого потомка') # метод доступа к левому потомку def get_left_child(self): - return self.left_child + if self.left_child: + return self.left_child + else: + print('Нет левого потомка') # метод установки корня def set_root_val(self, obj): - self.root = obj + if self.left_child.root < obj < self.right_child.root: + self.root = obj + else: + print('Impossible value') # метод доступа к корню def get_root_val(self): - return self.root + if self.root: + return self.root + else: + print('Нет корня') r = BinaryTree(8) -print(r.get_root_val()) -print(r.get_left_child()) -r.insert_left(40) -print(r.get_left_child()) -print(r.get_left_child().get_root_val()) +r.insert_left(12) +r.insert_left(4) +r.insert_right(2) r.insert_right(12) -print(r.get_right_child()) -print(r.get_right_child().get_root_val()) -r.get_right_child().set_root_val(16) -print(r.get_right_child().get_root_val()) \ No newline at end of file +print(r.get_root_val()) +print(r.left_child.get_left_child()) +print(r.left_child.get_right_child()) \ No newline at end of file