Welcome to a fascinating journey into the world of data compression! Today, we're going to learn about Huffman Coding, a fundamental algorithm in the field of data structures and algorithms. This technique is widely used for lossless data compression, making it a valuable skill for any developer. Let's get started!
Huffman Coding is a popular lossless data compression algorithm that assigns variable-length codes to input characters such that frequently occurring characters are assigned shorter codes. This makes it possible to represent data using fewer bits, thereby saving storage space or reducing transmission time.
Huffman Coding is appealing due to its efficiency, adaptability, and simplicity. Here are some reasons why:
Let's dive into the process of creating Huffman codes step by step:
Character | Frequency
----------|------------
'a' | 10
'b' | 5
'c' | 7
'd' | 3
'e' | 15

Character | Code
----------|------
'a' | 0
'b' | 10
'c' | 110
'd' | 1110
'e' | 1111
Let's implement Huffman Coding in Python:
def build_huffman_tree(frequencies):
heap = [(freq, char, Node(char, freq)) for char, freq in frequencies.items()]
while len(heap) > 1:
left, right = heap.pop(0), heap.pop(0)
parent = Node(None, left[0] + right[0])
parent.left = left[2]
parent.right = right[2]
heap.append((parent.freq, None, parent))
return parent
class Node:
def __init__(self, char, freq, left=None, right=None):
self.char = char
self.freq = freq
self.left = left
self.right = right
def compress(text, frequencies):
tree = build_huffman_tree(frequencies)
codes = {}
def assign_codes(node, code):
if node:
if node.char is not None:
codes[node.char] = code
if node.left:
assign_codes(node.left, code + '0')
if node.right:
assign_codes(node.right, code + '1')
assign_codes(tree, '')
compressed = ''.join(codes[char] for char in text)
return compressed, codes
def decompress(compressed, codes, root):
result = ''
def decode(node, code):
if node:
if node.char is not None:
result += node.char
if node.left and code == '0':
decode(node.left, code + '0')
if node.right and code == '1':
decode(node.right, code + '1')
start = 0
while start < len(compressed):
code = ''
while start + len(code) < len(compressed) and compressed[start + len(code)] == code[-1]:
code += compressed[start + len(code)]
decode(root, code)
start += len(code) + 1
return result
text = 'abbbbcdede'
frequencies = {'a': 10, 'b': 5, 'c': 7, 'd': 3, 'e': 15}
compressed, codes = compress(text, frequencies)
print('Compressed data:', compressed)
root = build_huffman_tree(frequencies)
decompressed = decompress(compressed, codes, root)
print('Decompressed data:', decompressed)What is Huffman Coding?
Why is Huffman Coding more efficient than other simple coding methods like ASCII encoding?
What is the purpose of the `build_huffman_tree` function in the provided implementation?
That's it for today! In the next lesson, we'll dive deeper into Huffman Coding and explore its applications, variations, and optimizations. Until then, happy coding! š»āØ