-
Notifications
You must be signed in to change notification settings - Fork 77
Hw 8 #578
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
leget1987
wants to merge
25
commits into
DmitryChitalov:master
Choose a base branch
from
leget1987:hw_8
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
Hw 8 #578
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
599c616
Первое задание домашки 1
leget1987 655b985
Дописал 2-5 задния
leget1987 3736465
подправил 5 задание
leget1987 4280aae
Добавил гитигнор
leget1987 a79498e
Добавил гитигнор
leget1987 4072cb7
удалил не нужные файлы
leget1987 54f6158
Сделал 6 задание
leget1987 bc95917
Сделал 7 задание
leget1987 e784d27
Сделал 8 задание
leget1987 9665b3c
Сделал 9 задание
leget1987 614b6e9
Оптимизировал код в 7, 8 и 9 задании
leget1987 3df1ad6
Сделал задание
leget1987 4ecc8ab
Удалил ненужные файлы
leget1987 a627bf7
New Revert "Сделал задание"
leget1987 7ddf6de
Окончательный вариант
leget1987 d16e788
test
leget1987 86051e6
test2
leget1987 1e2ebfd
Сделал ДЗ
leget1987 90e0c0d
удалил ненужные файлы
leget1987 5d2eb30
сделал ДЗ
leget1987 6f7986c
удалил не нужное дз
leget1987 1949781
Сделал ДЗ
leget1987 e2526ef
удалил не нужные файлы
leget1987 46eb825
ДЗ 8
leget1987 3b87147
удалил ненужные файлы
leget1987 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 was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
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
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 |
|---|---|---|
|
|
@@ -8,3 +8,61 @@ | |
| Результат: | ||
| 00 11 11 101 010 00 011 011 101 010 00 11 11 1000 1001 | ||
| """ | ||
| import heapq # модуль для работы с мин. кучей из стандартной библиотеки Python | ||
| from collections import Counter # словарь в котором для каждого объекта поддерживается счетчик | ||
| from collections import namedtuple | ||
|
|
||
|
|
||
| # добавим классы для хранения информации о структуре дерева | ||
| # воспользуемся функцией namedtuple из стандартной библиотеки | ||
| class Node(namedtuple("Node", ["left", "right"])): # класс для ветвей дерева - внутренних узлов; у них есть потомки | ||
| def walk(self, code, acc): | ||
| # чтобы обойти дерево нам нужно: | ||
| self.left.walk(code, acc + "0") # пойти в левого потомка, добавив к префиксу "0" | ||
| self.right.walk(code, acc + "1") # затем пойти в правого потомка, добавив к префиксу "1" | ||
|
|
||
|
|
||
| class Leaf(namedtuple("Leaf", ["char"])): # класс для листьев дерева, у него нет потомков, но есть значение символа | ||
| def walk(self, code, acc): | ||
| # потомков у листа нет, по этому для значения мы запишем построенный код для данного символа | ||
| code[self.char] = acc or "0" # если строка длиной 1 то acc = "", для этого случая установим значение acc = "0" | ||
|
|
||
|
|
||
| def huffman_encode(s): # функция кодирования строки в коды Хаффмана | ||
| h = [] # инициализируем очередь с приоритетами | ||
| for ch, freq in Counter(s).items(): # постоим очередь с помощью цикла, добавив счетчик, уникальный для всех листьев | ||
| h.append((freq, len(h), Leaf(ch))) # очередь будет представлена частотой символа, счетчиком и самим символом | ||
| heapq.heapify(h) # построим очередь с приоритетами | ||
| count = len(h) # инициализируем значение счетчика длиной очереди | ||
| while len(h) > 1: # пока в очереди есть хотя бы 2 элемента | ||
| freq1, _count1, left = heapq.heappop(h) # вытащим элемент с минимальной частотой - левый узел | ||
| freq2, _count2, right = heapq.heappop(h) # вытащим следующий элемент с минимальной частотой - правый узел | ||
| # поместим в очередь новый элемент, у которого частота равна суме частот вытащенных элементов | ||
| heapq.heappush(h, (freq1 + freq2, count, Node(left, right))) # добавим новый внутренний узел у которого | ||
| # потомки left и right соответственно | ||
| count += 1 # инкрементируем значение счетчика при добавлении нового элемента дерева | ||
| code = {} # инициализируем словарь кодов символов | ||
| if h: # если строка пустая, то очередь будет пустая и обходить нечего | ||
| [(_freq, _count, root)] = h # в очереди 1 элемент, приоритет которого не важен, а сам элемент - корень дерева | ||
| root.walk(code, "") # обойдем дерева от корня и заполним словарь для получения кодирования Хаффмана | ||
| return code # возвращаем словарь символов и соответствующих им кодов | ||
|
|
||
|
|
||
| def main(): | ||
| user_input = input("Введите строку: ") # читаем строку длиной до 10**4 | ||
| code = huffman_encode(user_input) # кодируем строку | ||
| encoded = "".join(code[ch] for ch in user_input) # отобразим закодированную версию, отобразив каждый символ | ||
| # в соответствующий код и конкатенируем результат | ||
| print(len(code), len(encoded)) # выведем число символов и длину закодированной строки | ||
| for ch in sorted(code): # обойдем символы в словаре в алфавитном порядке с помощью функции sorted() | ||
| print("{}: {}".format(ch, code[ch])) # выведем символ и соответствующий ему код | ||
| print(encoded) # выведем закодированную строку | ||
|
|
||
|
|
||
| main() | ||
|
|
||
| ''' | ||
| Почитал статью в интерненте, от туда же и взял код решения. Так жы пытался разобраться в кодах | ||
| из урока, если быть откровенным, очень тяжело осмыслить. Понял не все. В начале вроде все понятно, | ||
| но чем дальше погружаешься в код, тем меньше ясности. Буду дальше учиться. Спасибо за курс. | ||
| ''' | ||
|
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.
задание выполнено