U9
This commit is contained in:
parent
4e702378a8
commit
e42bb36f12
143
u9/huffman_tree.py
Normal file
143
u9/huffman_tree.py
Normal file
@ -0,0 +1,143 @@
|
||||
class HuffmanNode:
|
||||
def __init__(self, data=None, frequency=0, left=None, right=None):
|
||||
self.data = data
|
||||
self.frequency = frequency
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
||||
def __str__(self):
|
||||
if self.data is not None:
|
||||
return f"Node('{self.data}': {self.frequency})"
|
||||
else:
|
||||
return f"Node(freq: {self.frequency})"
|
||||
|
||||
|
||||
class HuffmanTree:
|
||||
def __init__(self, data):
|
||||
if not data:
|
||||
self.root = None
|
||||
self._codes_map = {}
|
||||
return
|
||||
|
||||
# Считаем частоты и запоминаем порядок первого появления символов
|
||||
counts = {}
|
||||
first_time_indx = {}
|
||||
for i, char in enumerate(data): # enumerate дает каждому символу его индекс
|
||||
if char not in counts:
|
||||
counts[char] = 0
|
||||
first_time_indx[char] = i
|
||||
counts[char] += 1
|
||||
|
||||
def get_first_index(char):
|
||||
return first_time_indx[char]
|
||||
# Пропускаем каждый уникальный символ через формулу get_first_index и сортируем по
|
||||
# возрастанию индекса первого появления
|
||||
unique_chars = sorted(counts.keys(), key=get_first_index)
|
||||
|
||||
# Инициализируем слова и смотрим какое раньше какое позже
|
||||
nodes = []
|
||||
order_index = 0
|
||||
for char in unique_chars:
|
||||
# node = (что за символ, частота появление)
|
||||
node = HuffmanNode(data=char, frequency=counts[char])
|
||||
nodes.append((node, order_index))
|
||||
order_index += 1
|
||||
|
||||
# Строим дерево пока не останется один корневой узел
|
||||
while len(nodes) > 1:
|
||||
# Сортируем список
|
||||
# При равной частоте решает время создания (кто создан раньше тот и первее)
|
||||
def huffman_sort_key(item):
|
||||
node = item[0] # сам узел
|
||||
order_index = item[1] # порядковый номер (order_index)
|
||||
return (node.frequency, order_index)
|
||||
|
||||
nodes.sort(key=huffman_sort_key)
|
||||
|
||||
# Забираем два узла с наименьшей частотой
|
||||
left_node, left_time = nodes.pop(0)
|
||||
right_node, right_time = nodes.pop(0)
|
||||
|
||||
# Создаем новый внутренний узел объединяющий их
|
||||
merged = HuffmanNode(
|
||||
data=None,
|
||||
frequency=left_node.frequency + right_node.frequency,
|
||||
left=left_node,
|
||||
right=right_node
|
||||
)
|
||||
|
||||
# Возращаем новый узел в список с новым порядковым индексом
|
||||
nodes.append((merged, order_index))
|
||||
order_index += 1
|
||||
|
||||
# Сохраняем корень
|
||||
self.root = nodes[0][0]
|
||||
|
||||
# Генерируем таблицу кодов
|
||||
self._codes_map = self._generate_codes()
|
||||
|
||||
def tree(self):
|
||||
return self.root
|
||||
|
||||
def _generate_codes(self):
|
||||
if not self.root:
|
||||
return {}
|
||||
|
||||
# Если в тексте только один уникальный символ
|
||||
if self.root.left is None and self.root.right is None:
|
||||
return {self.root.data: "0"}
|
||||
|
||||
codes = {}
|
||||
|
||||
# Рекурсивный обход дерева для составления кодов
|
||||
def traverse(node, current_code):
|
||||
if node.data is not None: # Это лист значит дошли до символа
|
||||
codes[node.data] = current_code
|
||||
return
|
||||
if node.left:
|
||||
traverse(node.left, current_code + "0")
|
||||
if node.right:
|
||||
traverse(node.right, current_code + "1")
|
||||
|
||||
traverse(self.root, "")
|
||||
return codes
|
||||
|
||||
def codes(self):
|
||||
return self._codes_map
|
||||
|
||||
def encode(self, text):
|
||||
if not self.root or not text:
|
||||
return ""
|
||||
# Просто подставляем код вместо каждой буквы
|
||||
# Создаем пустой список для кусочков кода
|
||||
result = []
|
||||
|
||||
for char in text:
|
||||
# Достаем из словаря код для этой буквы и добавляем в список
|
||||
code = self._codes_map[char]
|
||||
result.append(code)
|
||||
return "".join(result) # "" означают пробел между кусками типо (0, 11, 01)
|
||||
|
||||
def decode(self, bits):
|
||||
if not self.root or not bits:
|
||||
return ""
|
||||
|
||||
# Если в тексте только один уникальный символ
|
||||
if self.root.left is None and self.root.right is None:
|
||||
return self.root.data * len(bits)
|
||||
|
||||
decoded = []
|
||||
current = self.root
|
||||
|
||||
for bit in bits:
|
||||
if bit == "0":
|
||||
current = current.left
|
||||
else:
|
||||
current = current.right
|
||||
|
||||
# Если дошли до листа записываем символ и возвращаемся в корень
|
||||
if current.data is not None:
|
||||
decoded.append(current.data)
|
||||
current = self.root
|
||||
|
||||
return "".join(decoded)
|
||||
Loading…
Reference in New Issue
Block a user