diff --git a/u9/huffman_tree.py b/u9/huffman_tree.py index e35ce8a..0d25420 100644 --- a/u9/huffman_tree.py +++ b/u9/huffman_tree.py @@ -56,6 +56,31 @@ class HuffmanTree: return self.make_codes(node.left, path + "0") self.make_codes(node.right, path + "1") + def encode(self, text): + # zakodujeme text na nuly a jednotky + res = "" + for ch in text: + res += self.char_codes[ch] + return res + def decode(self, bits): + if not bits: + return " + if self.root.left is None and self.root.right is None: + return self.root.data * len(bits) + + # dekodujeme bity naspat na text + res = "" + curr = self.root + for b in bits: + if b == "0": + curr = curr.left + else: + curr = curr.right + + if curr.left is None and curr.right is None: + res += curr.data + curr = self.root + return res