Skip to content

Commit

Permalink
add: added Tables for HuffmanTree
Browse files Browse the repository at this point in the history
  • Loading branch information
warmachine028 committed Aug 3, 2023
1 parent 4a6da8d commit ad0c71d
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
54 changes: 54 additions & 0 deletions datastax/Tables/AbstractTables/HuffmanTable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from abc import ABC as AbstractClass, abstractmethod


class HuffmanTable(AbstractClass):
data: dict[str, str]
_frequencies: dict[str, int]
_size = 0

@property
def frequencies(self):
return self._frequencies

@property
def size(self):
return self._size

def __str__(self):
items = self.data
padding = 4
max_width = max(len(code) for *_, code in items.values()) + padding * 2
if max_width < 10:
max_width = 12
mid_width = max_width * 2 - (4 if max_width > 12 else 0)

h_border = f"╔{'═' * max_width}{'═' * mid_width}{'═' * max_width}\n"
header = (
f"║{'Unique'.center(max_width)}"
f"│{'Occurrence /'.center(mid_width)}│"
f"{'Huffman'.center(max_width)}\n"
f"║{'Characters'.center(max_width)}"
f"│{'Frequency'.center(mid_width)}│"
f"{'Code'.center(max_width)}\n"
)
sep = f"╟{'─' * max_width}{'─' * mid_width}{'─' * max_width}\n"
data_template = "║{}│{}│{}║\n"

body = ""
for character, huffman_code in items.items():
body += sep
body += data_template.format(
character.center(max_width),
str(self.frequencies[character]).center(mid_width),
huffman_code.rjust(max_width - padding).center(max_width),
)
f_border = f"╚{'═' * max_width}{'═' * mid_width}{'═' * max_width}╝"
return h_border + header + body + f_border

@abstractmethod
def set_frequencies(self, frequencies: dict):
...

@abstractmethod
def set_size(self):
...
5 changes: 5 additions & 0 deletions datastax/Tables/AbstractTables/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .HuffmanTable import HuffmanTable

__all__ = [
'HuffmanTable'
]
18 changes: 18 additions & 0 deletions datastax/Tables/HuffmanTable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from datastax.Tables.AbstractTables import HuffmanTable as AbstractTable


class HuffmanTable(AbstractTable):
def __init__(self, data: dict[str, str],
frequencies: dict[str, int]):
self.data = data
self.set_frequencies(frequencies)
self.set_size()

def set_size(self):
size = 0
for char, huff_code in self.data.items():
size += ord(char).bit_length() + len(huff_code)
self._size = size

def set_frequencies(self, frequencies: dict[str, int]):
self._frequencies = frequencies
5 changes: 5 additions & 0 deletions datastax/Tables/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .HuffmanTable import HuffmanTable

__all__ = [
'HuffmanTable'
]

0 comments on commit ad0c71d

Please sign in to comment.