35 lines
837 B
Python
35 lines
837 B
Python
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
|
|
|
|
|
|
class HuffmanTree:
|
|
def __init__(self, data):
|
|
self.root = None
|
|
self.char_codes = {}
|
|
|
|
if not data:
|
|
return
|
|
|
|
# spocitame krat znakov
|
|
freq = {}
|
|
for ch in data:
|
|
if ch in freq:
|
|
freq[ch] += 1
|
|
else:
|
|
freq[ch] = 1
|
|
|
|
# ak je len jeden typ
|
|
if len(freq) == 1:
|
|
ch = data[0]
|
|
self.root = HuffmanNode(ch, freq[ch])
|
|
self.char_codes[ch] = "0"
|
|
return
|
|
|
|
# zoznam listov
|
|
nodes = []
|
|
for ch in freq:
|
|
nodes.append(HuffmanNode(ch, freq[ch])) |