-
Notifications
You must be signed in to change notification settings - Fork 173
lesson 8 completed finally #1278
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| """ | ||
| Задание 1. | ||
| Реализуйте кодирование строки "по Хаффману". | ||
| У вас два пути: | ||
| 1) тема идет тяжело? тогда вы можете, опираясь на пример с урока, сделать свою версию алгоритма | ||
| Разрешается и приветствуется изменение имен переменных, выбор других коллекций, различные изменения | ||
| и оптимизации. | ||
| КОПИПАСТ ПРИМЕРА ПРИНИМАТЬСЯ НЕ БУДЕТ! | ||
| 2) тема понятна? постарайтесь сделать свою реализацию. | ||
| Вы можете реализовать задачу, например, через ООП или предложить иной подход к решению. | ||
|
|
||
| ВНИМАНИЕ: примеры заданий будут размещены в последний день сдачи. | ||
| Но постарайтесь обойтись без них. | ||
| """ | ||
|
|
||
| import queue | ||
|
|
||
| #Узел | ||
| class Node: | ||
| def __init__(self, x, k=-1, l=None, r=None, c=''): | ||
| self.freq = x | ||
| self.key = k | ||
| self.left = l | ||
| self.right = r | ||
| self.code = c | ||
|
|
||
| def __lt__(self, otr): | ||
| return self.freq < otr.freq | ||
|
|
||
| #Декодер | ||
| def huffman_decoder(code_table, data): | ||
| decoder = [] | ||
| for s in data: | ||
| for key_1 in code_table: | ||
| if s == key_1: | ||
| decoder.append(code_table[key_1]) | ||
| return " ".join(decoder) | ||
|
|
||
|
|
||
| #Словарь из символов и количества вхождений | ||
| def huffman_code(data): | ||
| freqTable = {} | ||
| nodeList = [] | ||
| que = queue.PriorityQueue() | ||
| codeTable = {} | ||
|
|
||
| for n in data: | ||
| if n in freqTable: | ||
| freqTable[n] += 1 | ||
| else: | ||
| freqTable[n] = 1 | ||
|
|
||
| for k, v in freqTable.items(): | ||
| nodeList.append(Node(v, k)) | ||
| que.put(nodeList[-1]) | ||
|
|
||
| while que.qsize() > 1: | ||
| n1 = que.get() | ||
| n2 = que.get() | ||
| n1.code = '1' | ||
| n2.code = '0' | ||
| nn = Node(n1.freq + n2.freq, l=n1, r=n2); | ||
| nodeList.append(nn); | ||
| que.put(nodeList[-1]) | ||
|
|
||
| def bl(p, codestr=[]): | ||
|
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. такие имена ф-ций - шифрокоддругие разработчики не поймут что делает ф-ция
Author
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.
Спасибо! Согласен, нужно было это учитывать. |
||
| codestr.append(p.code) | ||
| if p.left: | ||
| bl(p.left, codestr.copy()) | ||
| bl(p.right, codestr.copy()) | ||
| else: | ||
| codeTable[p.key] = ''.join(codestr) | ||
|
|
||
| bl(nodeList[-1]) | ||
| #После получения используем декодер | ||
| return huffman_decoder(codeTable, data) | ||
|
|
||
|
|
||
|
|
||
|
|
||
| #Пользовательский код | ||
| if __name__ == '__main__': | ||
|
|
||
| user_input = input("Введите строку: ") | ||
| huff_list = [] | ||
| for i in user_input: | ||
| huff_list.append(i) | ||
| huff_code = huffman_code(huff_list) | ||
| print(huff_code) | ||
|
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. нет решения второй задачи |
||
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.
допустим ли такой стиль по пеп-8??
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.
он недопустим
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.
Спасибо! Да, нужно было через нижнее подчеркивание (а лучше - максимально упрощенно, одним словом), а не CamelCase. Теперь не перепутаю.