From af21b48132f104d49b3fd582b86f5552980fbf14 Mon Sep 17 00:00:00 2001 From: dpittaluga76 Date: Wed, 16 Jun 2021 15:09:21 -0300 Subject: [PATCH 1/2] 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. --- compression/huffman.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/compression/huffman.py b/compression/huffman.py index 3a3cbfa4b0c6..8b8310f56476 100644 --- a/compression/huffman.py +++ b/compression/huffman.py @@ -1,11 +1,10 @@ import sys - class Letter: def __init__(self, letter, freq): self.letter = letter self.freq = freq - self.bitstring = "" + self.bitstring = {} def __repr__(self): return f"{self.letter}:{self.freq}" @@ -51,10 +50,10 @@ def build_tree(letters): def traverse_tree(root, bitstring): """ Recursively traverse the Huffman Tree to set each - Letter's bitstring, and return the list of Letters + Letter's bitstring dictionary, and return the list of Letters """ if type(root) is Letter: - root.bitstring = bitstring + root.bitstring[root.letter] = bitstring return [root] letters = [] letters += traverse_tree(root.left, bitstring + "0") @@ -65,20 +64,20 @@ def traverse_tree(root, bitstring): def huffman(file_path): """ Parse the file, build the tree, then run through the file - again, using the list of Letters to find and print out the + again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) - letters = traverse_tree(root, "") - print(f"Huffman Coding of {file_path}: ") + letters = {k: v for letter in traverse_tree(root, "") + for k, v in letter.bitstring.items()} + print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break - le = list(filter(lambda l: l.letter == c, letters))[0] - print(le.bitstring, end=" ") + print(letters[c], end=" ") print() From 36f9b64398895b0bfce22bc07c2c98894586b04e Mon Sep 17 00:00:00 2001 From: dpittaluga76 Date: Thu, 1 Jul 2021 21:13:12 -0300 Subject: [PATCH 2/2] Update huffman.py --- compression/huffman.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/compression/huffman.py b/compression/huffman.py index 8b8310f56476..b6cc4de1e8e6 100644 --- a/compression/huffman.py +++ b/compression/huffman.py @@ -1,5 +1,6 @@ import sys + class Letter: def __init__(self, letter, freq): self.letter = letter @@ -69,8 +70,9 @@ def huffman(file_path): """ letters_list = parse_file(file_path) root = build_tree(letters_list) - letters = {k: v for letter in traverse_tree(root, "") - for k, v in letter.bitstring.items()} + letters = { + k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() + } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: