Skip to content

Commit 2cbadc8

Browse files
authored
Improves readability and processing time (TheAlgorithms#4510)
* Removes overuse of lambdas, improves readability and processing time when it finds bitstring to print out. Removes overuse of lambdas, uses dictionary instead. This improves readability and processing time when it finds the bitstring to print out. * Update huffman.py
1 parent 307ffd8 commit 2cbadc8

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

compression/huffman.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ class Letter:
55
def __init__(self, letter, freq):
66
self.letter = letter
77
self.freq = freq
8-
self.bitstring = ""
8+
self.bitstring = {}
99

1010
def __repr__(self):
1111
return f"{self.letter}:{self.freq}"
@@ -51,10 +51,10 @@ def build_tree(letters):
5151
def traverse_tree(root, bitstring):
5252
"""
5353
Recursively traverse the Huffman Tree to set each
54-
Letter's bitstring, and return the list of Letters
54+
Letter's bitstring dictionary, and return the list of Letters
5555
"""
5656
if type(root) is Letter:
57-
root.bitstring = bitstring
57+
root.bitstring[root.letter] = bitstring
5858
return [root]
5959
letters = []
6060
letters += traverse_tree(root.left, bitstring + "0")
@@ -65,20 +65,21 @@ def traverse_tree(root, bitstring):
6565
def huffman(file_path):
6666
"""
6767
Parse the file, build the tree, then run through the file
68-
again, using the list of Letters to find and print out the
68+
again, using the letters dictionary to find and print out the
6969
bitstring for each letter.
7070
"""
7171
letters_list = parse_file(file_path)
7272
root = build_tree(letters_list)
73-
letters = traverse_tree(root, "")
74-
print(f"Huffman Coding of {file_path}: ")
73+
letters = {
74+
k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()
75+
}
76+
print(f"Huffman Coding of {file_path}: ")
7577
with open(file_path) as f:
7678
while True:
7779
c = f.read(1)
7880
if not c:
7981
break
80-
le = list(filter(lambda l: l.letter == c, letters))[0]
81-
print(le.bitstring, end=" ")
82+
print(letters[c], end=" ")
8283
print()
8384

8485

0 commit comments

Comments
 (0)