Create a program that performs Huffman coding for data compression.
- User
Create a program that performs Huffman coding for data compression.
Assistant
Create a program that performs Huffman coding for data compression.
1. Understand the Goal: The user wants a program to perform Huffman coding for data compression. This means I need to implement the core logic of the algorithm: frequency counting, priority queue (min-heap), tree building, code generation, and optionally encoding/decoding strings.
Determine the Language: Python is the best choice for this. It's readable, widely used for algorithms, and has built-in data structures (like heapq and collections.Counter) that make the implementation clean.
Algorithm Breakdown (Huffman Coding):
Implementation Details (Python):
Node. It needs char, freq, left, and right. To make heapq work with objects, I need to implement __lt__ (less than).import heapq.Drafting the Code (Mental or Scratchpad):
import heapq
class Node:
def __init__(self, freq, char=None, left=None, right=None):
self.freq = freq
self.char = char
self.left = left
self.right = right
# Crucial for heapq to compare nodes
def __lt__(self, other):
return self.freq < other.freq
def build_tree(text):
# 1. Count frequencies
from collections import Counter
counts = Counter(text)
# 2. Create heap
heap = [Node(freq=c, char=char) for char, c in counts.items()]
heapq.heapify(heap)
# 3. Build tree
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
# Internal node has no char, just sum of freqs
merged = Node(freq=left.freq + right.freq, left=left, right=right)
heapq.heappush(heap, merged)
return heap[0] # Root
Refining Code Generation:
Need a helper function generate_codes(node, current_code, codes_dict).
def generate_codes(node, current_code, codes):
if node is None: return
if node.char is not None:
# It's a leaf
codes[node.char] = current_code
return
generate_codes(node.left, current_code + "0", codes)
generate_codes(node.right, current_code + "1", codes)
Structuring the Output:
Handling Edge Cases:
len > 1 doesn't run. Tree is just the root. Code generation needs to handle root being a leaf (assign "0").Final Code Assembly:
Review against Prompt:
Adding Explanation: Briefly explain why Huffman coding works (variable-length codes, prefix-free property) to make the answer more educational.
Final Polish: Ensure variables are named descriptively (freq, char, encoded_text). Check imports.
(Self-Correction during drafting): I initially forgot to implement __lt__ in the Node class. Without this, heapq throws an error if two nodes have the same frequency but are objects. I must ensure that is included. I should also verify that tie-breaking logic (using char comparison) isn't strictly necessary for the algorithm to work, though it helps determinism. I'll stick to just frequency comparison for simplicity, as standard Python object comparison is handled if needed, or just rely on insertion order stability for ties. Actually, simple frequency comparison is enough for the algorithm to function correctly.
Let's write the final code structure.
HuffmanNodebuild_huffman_tree(text)generate_codes(root)encode_text(text, codes)decode_text(encoded_text, root) (Bonus)main block to tie it all together.This looks solid. I will proceed with generating the Python solution. Here is a complete, object-oriented Python program that implements Huffman Coding.
This implementation includes:
Frequency Analysis (make_frequency_dict):
The algorithm starts by counting how often each character appears. Characters that appear frequently (like 'a' in the example) should have shorter codes, while rare characters get longer codes.
Building the Heap (make_heap):
We create a leaf node for each character and add it to a Min-Heap. A Min-Heap ensures that we can always efficiently retrieve the two nodes with the lowest frequencies.
Building the Tree (merge_nodes):
We pop the two nodes with the lowest frequencies. We create a new internal node whose frequency is the sum of the two children. This new node becomes the parent of the two popped nodes. We push this new node back into the heap. We repeat this until only one node remains (the Root).
Generating Codes (make_codes):
We traverse the tree recursively.
0 to the code.1 to the code.Encoding (get_encoded_text):
We simply replace every character in the input string with its new binary code.
Decompression (decompress):
We traverse the binary string bit by bit. We accumulate bits until the sequence matches a code in our reverse-mapping dictionary. Once a match is found, we append the character to the result and reset the accumulator.
import heapq
import os
from collections import Counter
class HuffmanNode:
"""
A node class for the Huffman Tree.
Comparable capability is added for the priority queue.
"""
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
# Defining comparators less_than and equals
def __lt__(self, other):
return self.freq < other.freq
def __eq__(self, other):
if other == None:
return False
if not isinstance(other, HuffmanNode):
return False
return self.freq == other.freq
class HuffmanCoding:
def __init__(self, path=None):
self.path = path
self.heap = []
self.codes = {}
self.reverse_mapping = {}
# --- Compression Steps ---
def make_frequency_dict(self, text):
"""Count frequency of each character."""
return Counter(text)
def make_heap(self, frequency):
"""Create a priority queue (min-heap) of nodes."""
for key in frequency:
node = HuffmanNode(key, frequency[key])
heapq.heappush(self.heap, node)
def merge_nodes(self):
"""Build the Huffman Tree by merging nodes."""
while len(self.heap) > 1:
node1 = heapq.heappop(self.heap)
node2 = heapq.heappop(self.heap)
merged = HuffmanNode(None, node1.freq + node2.freq)
merged.left = node1
merged.right = node2
heapq.heappush(self.heap, merged)
def make_codes_helper(self, root, current_code):
"""Recursive helper to generate binary codes."""
if root is None:
return
# If it is a leaf node (contains a character)
if root.char is not None:
self.codes[root.char] = current_code
self.reverse_mapping[current_code] = root.char
return
self.make_codes_helper(root.left, current_code + "0")
self.make_codes_helper(root.right, current_code + "1")
def make_codes(self):
"""Initiate code generation from the root."""
root = heapq.heappop(self.heap)
current_code = ""
self.make_codes_helper(root, current_code)
def get_encoded_text(self, text):
"""Replace characters with their binary codes."""
encoded_text = ""
for character in text:
encoded_text += self.codes[character]
return encoded_text
def compress(self, text):
"""Main compression function."""
# 1. Calculate frequencies
frequency = self.make_frequency_dict(text)
# 2. Create min-heap
self.make_heap(frequency)
# 3. Build tree
self.merge_nodes()
# 4. Generate codes
self.make_codes()
# 5. Encode text
encoded_text = self.get_encoded_text(text)
return encoded_text
# --- Decompression Step ---
def decompress(self, encoded_text):
"""Convert binary string back to original text."""
current_code = ""
decoded_text = ""
for bit in encoded_text:
current_code += bit
if current_code in self.reverse_mapping:
character = self.reverse_mapping[current_code]
decoded_text += character
current_code = ""
return decoded_text
# --- Main Execution ---
if __name__ == "__main__":
# Sample text containing varied frequencies
# 'a' appears often, others less so.
text = "aaaaaaabbbbbcccccdddddeeeefff"
print(f"Original Text: {text}")
print(f"Original Size (approx): {len(text) * 8} bits (ASCII)")
huffman = HuffmanCoding()
# Compress
encoded = huffman.compress(text)
print(f"\nEncoded String: {encoded}")
print(f"Compressed Size: {len(encoded)} bits")
# Calculate Compression Ratio
ratio = (len(encoded) / (len(text) * 8)) * 100
print(f"Compression Ratio: {ratio:.2f}% of original size")
# Decompress
decoded = huffman.decompress(encoded)
print(f"\nDecoded Text: {decoded}")
# Verify correctness
if text == decoded:
print("\nSUCCESS: Decompressed text matches original.")
else:
print("\nERROR: Data mismatch.")