0% found this document useful (0 votes)
7 views

Huffman Coding

The document provides a Python implementation of Huffman coding, which is a method for compressing data based on character frequencies. It constructs a binary tree to generate unique binary codes for each character, ensuring that more frequent characters have shorter codes. The example demonstrates how to use the function with a set of characters and their corresponding frequencies, outputting the resulting Huffman codes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Huffman Coding

The document provides a Python implementation of Huffman coding, which is a method for compressing data based on character frequencies. It constructs a binary tree to generate unique binary codes for each character, ensuring that more frequent characters have shorter codes. The example demonstrates how to use the function with a set of characters and their corresponding frequencies, outputting the resulting Huffman codes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Huffman Coding

def huffman_coding(chars, freqs):

nodes = [(chars[i], freqs[i]) for i in range(len(chars))]

n = len(nodes)

while n > 1:

for i in range(n - 1):

for j in range(n - i - 1):

if nodes[j][1] > nodes[j + 1][1]:

nodes[j], nodes[j + 1] = nodes[j + 1], nodes[j]

left = nodes[0]

right = nodes[1]

merged = (None, left[1] + right[1])

for i in range(2, n):

nodes[i - 2] = nodes[i]

nodes[n - 2] = merged

n -= 1

root = nodes[0]

huffman_codes = {}

queue = [(root, "")] # Queue to simulate the tree traversal

while queue:

current_node, current_code = queue.pop(0)

if current_node[0] is not None:

huffman_codes[current_node[0]] = current_code

else:

left = current_node[0][0]

right = current_node[0][1]

if left:

queue.append((left, current_code + "0"))

if right:

queue.append((right, current_code + "1"))

return huffman_codes

chars = ['a', 'b', 'c', 'd', 'e', 'f']


freqs = [5, 9, 12, 13, 16, 45]

huffman_codes = huffman_coding(chars, freqs)

print("Huffman Codes:")

for char, code in huffman_codes.items():

print(f"{char}: {code}")

You might also like