diff --git a/dyn_huffman.py b/dyn_huffman.py index 494bfb1113f9cd72f240af23202a62f63fabd44d..e7e737bb833cce74d0238aeca54c17fd72d55903 100644 --- a/dyn_huffman.py +++ b/dyn_huffman.py @@ -10,6 +10,8 @@ LIST_ALPHABET = list(string.ascii_lowercase) + list(string.digits) # LIST_ALPHABET = list(string.ascii_lowercase) DICT_ALPHABET = {item: index + 1 for index, item in enumerate(LIST_ALPHABET)} +swap_count = 0 + @dataclass class Node: weight: int = 0 @@ -20,9 +22,11 @@ class Node: def swap(tree: Node): + global swap_count if tree.left and tree.right: if tree.left.weight > tree.right.weight: - print(f'({tree.left.weight}, {tree.right.weight})') + # print(f'({tree.left.weight}, {tree.right.weight})') + swap_count += 1 tmp = tree.right tree.right = tree.left tree.left = tmp @@ -127,7 +131,7 @@ def compute_code(char: str): return bin(bin_val)[2:].zfill(e) -def encode(string: str) -> list[str]: +def encode(string: str) -> str: tree = Node() encoded: list[str] = [] seen: set[str] = set() @@ -141,14 +145,19 @@ def encode(string: str) -> list[str]: encoded.append(prefix.nyt_code) encoded.append(compute_code(c)) else: + print(f'{c} already seen') encoded.append(compute_prefix(tree, c)) + + pprint.pp(tree) + print(f'Nombre de swaps: {swap_count}') + return ' '.join(encoded)[1:] def main(string: str) -> None: msg = encode(string) - print(msg) + print(f'Code final: {msg}') # def main(string: str) -> None: # tree = Node()