From 8cf6c914d8c64e94a6b78a7e9923ed615d85f9fd Mon Sep 17 00:00:00 2001 From: "iliya.saroukha" <iliya.saroukhanian@etu.hesge.ch> Date: Thu, 10 Apr 2025 17:14:49 +0200 Subject: [PATCH] feat: insertion seemingly working for unknown characters --- dyn_huffman.py | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 dyn_huffman.py diff --git a/dyn_huffman.py b/dyn_huffman.py new file mode 100644 index 0000000..8e69633 --- /dev/null +++ b/dyn_huffman.py @@ -0,0 +1,86 @@ +from __future__ import annotations +from dataclasses import dataclass +import numpy as np +import pprint +import math +import argparse + +@dataclass +class Node: + weight: int = 0 + value: str | None = "NYT" + left: Node | None = None + right: Node | None = None + + +def char_in_tree(tree: Node, char: str) -> Node | None: + if tree.left != None: + char_in_tree(tree.left, char) + elif tree.right != None: + char_in_tree(tree.right, char) + + if tree.value == char: + return tree + else: + return None + + +def swap(tree: Node): + if tree.left and tree.right: + # print("weeeeeeeeeeeeeeesh") + if tree.left.weight > tree.right.weight: + print(f'({tree.left.weight}, {tree.right.weight})') + tmp = tree.right + tree.right = tree.left + tree.left = tmp + +def insert_char(tree: Node, char: str): + # Leaf case + if tree.left == None and tree.right == None: + tree.left = Node() + tree.right = Node(value=char, weight=1) + tree.weight += 1 + return + + if tree.left: + if tree.left.value == 'NYT': + insert_char(tree.left, char) + else: + if tree.right: + insert_char(tree.right, char) + + + tree.weight += 1 + swap(tree) + +def compute_vitter_params(m: int) -> (int, int): + e = math.floor(np.log2(m)) + r = m - (2 ** e) + + return (e, r) + + +def main(string: str) -> None: + print(compute_vitter_params(26)) + + tree = Node() + + for c in string: + pprint.pp(tree) + print(f'\n====== Inserting \'{c}\' ======\n') + insert_char(tree, c) + + pprint.pp(tree) + + # pprint.pp(tree) + + + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(prog='dyn_huffman.py') + parser.add_argument('string') + + args = parser.parse_args() + + main(args.string) -- GitLab