Skip to content

Commit e49d8e3

Browse files
authored
[mypy] annotate compression (TheAlgorithms#5570)
1 parent de07245 commit e49d8e3

File tree

4 files changed

+40
-28
lines changed

4 files changed

+40
-28
lines changed

compression/burrows_wheeler.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
"""
1313
from __future__ import annotations
1414

15+
from typing import TypedDict
16+
17+
18+
class BWTTransformDict(TypedDict):
19+
bwt_string: str
20+
idx_original_string: int
21+
1522

1623
def all_rotations(s: str) -> list[str]:
1724
"""
@@ -43,7 +50,7 @@ def all_rotations(s: str) -> list[str]:
4350
return [s[i:] + s[:i] for i in range(len(s))]
4451

4552

46-
def bwt_transform(s: str) -> dict:
53+
def bwt_transform(s: str) -> BWTTransformDict:
4754
"""
4855
:param s: The string that will be used at bwt algorithm
4956
:return: the string composed of the last char of each row of the ordered
@@ -75,10 +82,11 @@ def bwt_transform(s: str) -> dict:
7582
rotations = all_rotations(s)
7683
rotations.sort() # sort the list of rotations in alphabetically order
7784
# make a string composed of the last char of each rotation
78-
return {
85+
response: BWTTransformDict = {
7986
"bwt_string": "".join([word[-1] for word in rotations]),
8087
"idx_original_string": rotations.index(s),
8188
}
89+
return response
8290

8391

8492
def reverse_bwt(bwt_string: str, idx_original_string: int) -> str:

compression/huffman.py

+26-22
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
1+
from __future__ import annotations
2+
13
import sys
24

35

46
class Letter:
5-
def __init__(self, letter, freq):
6-
self.letter = letter
7-
self.freq = freq
8-
self.bitstring = {}
7+
def __init__(self, letter: str, freq: int):
8+
self.letter: str = letter
9+
self.freq: int = freq
10+
self.bitstring: dict[str, str] = {}
911

10-
def __repr__(self):
12+
def __repr__(self) -> str:
1113
return f"{self.letter}:{self.freq}"
1214

1315

1416
class TreeNode:
15-
def __init__(self, freq, left, right):
16-
self.freq = freq
17-
self.left = left
18-
self.right = right
17+
def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):
18+
self.freq: int = freq
19+
self.left: Letter | TreeNode = left
20+
self.right: Letter | TreeNode = right
1921

2022

21-
def parse_file(file_path):
23+
def parse_file(file_path: str) -> list[Letter]:
2224
"""
2325
Read the file and build a dict of all letters and their
2426
frequencies, then convert the dict into a list of Letters.
2527
"""
26-
chars = {}
28+
chars: dict[str, int] = {}
2729
with open(file_path) as f:
2830
while True:
2931
c = f.read(1)
@@ -33,36 +35,38 @@ def parse_file(file_path):
3335
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
3436

3537

36-
def build_tree(letters):
38+
def build_tree(letters: list[Letter]) -> Letter | TreeNode:
3739
"""
3840
Run through the list of Letters and build the min heap
3941
for the Huffman Tree.
4042
"""
41-
while len(letters) > 1:
42-
left = letters.pop(0)
43-
right = letters.pop(0)
43+
response: list[Letter | TreeNode] = letters # type: ignore
44+
while len(response) > 1:
45+
left = response.pop(0)
46+
right = response.pop(0)
4447
total_freq = left.freq + right.freq
4548
node = TreeNode(total_freq, left, right)
46-
letters.append(node)
47-
letters.sort(key=lambda l: l.freq)
48-
return letters[0]
49+
response.append(node)
50+
response.sort(key=lambda l: l.freq)
51+
return response[0]
4952

5053

51-
def traverse_tree(root, bitstring):
54+
def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
5255
"""
5356
Recursively traverse the Huffman Tree to set each
5457
Letter's bitstring dictionary, and return the list of Letters
5558
"""
5659
if type(root) is Letter:
5760
root.bitstring[root.letter] = bitstring
5861
return [root]
62+
treenode: TreeNode = root # type: ignore
5963
letters = []
60-
letters += traverse_tree(root.left, bitstring + "0")
61-
letters += traverse_tree(root.right, bitstring + "1")
64+
letters += traverse_tree(treenode.left, bitstring + "0")
65+
letters += traverse_tree(treenode.right, bitstring + "1")
6266
return letters
6367

6468

65-
def huffman(file_path):
69+
def huffman(file_path: str) -> None:
6670
"""
6771
Parse the file, build the tree, then run through the file
6872
again, using the letters dictionary to find and print out the

compression/lempel_ziv.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def read_file_binary(file_path: str) -> str:
2626

2727

2828
def add_key_to_lexicon(
29-
lexicon: dict, curr_string: str, index: int, last_match_id: str
29+
lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str
3030
) -> None:
3131
"""
3232
Adds new strings (curr_string + "0", curr_string + "1") to the lexicon
@@ -110,7 +110,7 @@ def write_file_binary(file_path: str, to_write: str) -> None:
110110
sys.exit()
111111

112112

113-
def compress(source_path, destination_path: str) -> None:
113+
def compress(source_path: str, destination_path: str) -> None:
114114
"""
115115
Reads source file, compresses it and writes the compressed result in destination
116116
file

compression/peak_signal_to_noise_ratio.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import numpy as np
1313

1414

15-
def psnr(original, contrast):
15+
def psnr(original: float, contrast: float) -> float:
1616
mse = np.mean((original - contrast) ** 2)
1717
if mse == 0:
1818
return 100
@@ -21,7 +21,7 @@ def psnr(original, contrast):
2121
return PSNR
2222

2323

24-
def main():
24+
def main() -> None:
2525
dir_path = os.path.dirname(os.path.realpath(__file__))
2626
# Loading images (original image and compressed image)
2727
original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png"))

0 commit comments

Comments
 (0)