Question: import heapq from collections import defaultdict class HuffmanNode: def _ _ init _ _ ( self , char, freq ) : self.char = char self.freq

import heapq
from collections import defaultdict
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
# Comparator for the priority queue
def __lt__(self, other):
return self.freq other.freq
def calculate_huffman_codes(frequencies):
# Priority queue for building the tree
heap =[HuffmanNode(char, freq) for char, freq in frequencies.items()]
heapq.heapify(heap)
print("
Step-by-step Tree Building:")
while len(heap)>1:
# Pop the two smallest nodes
left = heapq.heappop(heap)
right = heapq.heappop(heap)
# Combine these two nodes into a new parent node
merged = HuffmanNode(None, left.freq + right.freq)
merged.left = left
merged.right = right
# Push the parent node back into the priority queue
heapq.heappush(heap, merged)
print(f"Combined nodes with frequencies {left.freq} and {right.freq} into {merged.freq}")
# The root of the tree
root = heap[0]
# Recursively assign codes
codes ={}
def assign_codes(node, code=""):
if node is not None:
if node.char is not None:
codes[node.char]= code
assign_codes(node.left, code +"0")
assign_codes(node.right, code +"1")
assign_codes(root)
print("
Final Huffman Codes:")
for char, code in codes.items():
print(f"{char}: {code}")
return codes
# Input frequencies
frequencies ={
'a': 10,
'b': 2,
'c': 4,
'd': 5,
'e': 15,
'f': 9,
'g': 6,
'h': 8,
'i': 12,
'j': 1
}
# Run the Huffman coding algorithm
codes = calculate_huffman_codes(frequencies)
import heapq from collections import defaultdict

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!