-
Notifications
You must be signed in to change notification settings - Fork 77
hw 8 verkh #591
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
VerkhVektor
wants to merge
1
commit into
DmitryChitalov:master
Choose a base branch
from
VerkhVektor: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 verkh #591
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
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,85 @@ | |
| Результат: | ||
| 00 11 11 101 010 00 011 011 101 010 00 11 11 1000 1001 | ||
| """ | ||
|
|
||
| from collections import Counter, deque | ||
|
|
||
|
|
||
| def haffman_tree(s): | ||
| count = Counter(s) # Получаем частоты каждого элемента | ||
| sorted_elements = deque(sorted(count.items(), key=lambda item: item[1])) # Создаем очередь по возрастанию частот | ||
| # Проверка, если строка состоит из одного повторяющего символа. | ||
| if len(sorted_elements) != 1: | ||
| # Цикл для построения дерева | ||
| while len(sorted_elements) > 1: | ||
| weight = sorted_elements[0][1] + sorted_elements[1][1] # Суммируем частоты двух левых элементов лчереди | ||
| ''' | ||
| {0: 'r', 1: '!'} | ||
| {0: {0: 'r', 1: '!'}, 1: 'p'} | ||
| {0: ' ', 1: 'o'} | ||
| {0: 'b', 1: {0: ' ', 1: 'o'}} | ||
| {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'} | ||
| {0: {0: 'b', 1: {0: ' ', 1: 'o'}}, 1: {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}} | ||
| ''' | ||
| comb = {0: sorted_elements.popleft()[0], # Создаем узлы дерева 0 b 1. popleft удаляет элемент из очереди | ||
| 1: sorted_elements.popleft()[0]} # и возвращает значение | ||
|
|
||
| # Ищем место для ставки объединенного элемента | ||
| for i, _count in enumerate(sorted_elements): | ||
| if weight > _count[1]: # Если частота больше частоты iого элемента, то считаем дальше | ||
| continue | ||
| else: | ||
| sorted_elements.insert(i, (comb, weight)) # Если меньше, то вставляем узел | ||
| break | ||
| else: | ||
| # Добавляем объединенный корневой элемент после | ||
| # завершения работы цикла | ||
|
|
||
| sorted_elements.append((comb, weight)) | ||
| ''' | ||
| deque([({0: 'r', 1: '!'}, 2), ('p', 2), (' ', 2), ('o', 2), ('b', 3), ('e', 4)]) | ||
| deque([(' ', 2), ('o', 2), ('b', 3), ({0: {0: 'r', 1: '!'}, 1: 'p'}, 4), ('e', 4)]) | ||
| deque([('b', 3), ({0: ' ', 1: 'o'}, 4), ({0: {0: 'r', 1: '!'}, 1: 'p'}, 4), ('e', 4)]) | ||
| deque([({0: {0: 'r', 1: '!'}, 1: 'p'}, 4), ('e', 4), ({0: 'b', 1: {0: ' ', 1: 'o'}}, 7)]) | ||
| deque([({0: 'b', 1: {0: ' ', 1: 'o'}}, 7), ({0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}, 8)]) | ||
| deque([({0: {0: 'b', 1: {0: ' ', 1: 'o'}}, 1: {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}}, 15)]) | ||
| ''' | ||
| else: | ||
| # приравниваемыем значение 0 к одному повторяющемуся символу | ||
| weight = sorted_elements[0][1] | ||
| comb = {0: sorted_elements.popleft()[0], 1: None} | ||
| sorted_elements.append((comb, weight)) | ||
| # sorted_elements - deque([({0: {0: 'b', 1: {0: ' ', 1: 'o'}}, 1: {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}}, 15)]) | ||
| # {0: {0: 'b', 1: {0: ' ', 1: 'o'}}, 1: {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}} | ||
| # словарь - дерево | ||
| return sorted_elements[0][0] | ||
|
|
||
|
|
||
| code_table = dict() | ||
|
|
||
| # tree - {0: {0: 'b', 1: {0: ' ', 1: 'o'}}, 1: {0: {0: {0: 'r', 1: '!'}, 1: 'p'}, 1: 'e'}} | ||
| def haffman_code(tree, path=''): | ||
| # Если элемент не словарь, значит мы достигли самого символа | ||
| # и заносим его, а так же его код в словарь (кодовую таблицу). | ||
| if not isinstance(tree, dict): | ||
| code_table[tree] = path | ||
| # Если элемент словарь, рекурсивно спускаемся вниз | ||
| # по первому и второму значению (левая и правая ветви). | ||
| else: | ||
| haffman_code(tree[0], path=f'{path}0') | ||
| haffman_code(tree[1], path=f'{path}1') | ||
|
|
||
|
|
||
| # строка для кодирования | ||
| s = "beep boop beer!" | ||
|
|
||
| # функция заполняет кодовую таблицу (символ-его код) | ||
| # {'b': '00', ' ': '010', 'o': '011', 'r': '1000', '!': '1001', 'p': '101', 'e': '11'} | ||
| haffman_code(haffman_tree(s)) | ||
|
|
||
| # code_table - {'b': '00', ' ': '010', 'o': '011', 'r': '1000', '!': '1001', 'p': '101', 'e': '11'} | ||
|
|
||
| # выводим коды для каждого символа | ||
| for i in s: | ||
| print(code_table[i], end=' ') | ||
| print() | ||
|
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.
задание выполнено
плюс за документир-е кода