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 initself char, freq:
self.char char
self.freq freq
self.left None
self.right None
# Comparator for the priority queue
def ltself other:
return self.freq other.freq
def calculatehuffmancodesfrequencies:
# Priority queue for building the tree
heap HuffmanNodechar freq for char, freq in frequencies.items
heapq.heapifyheap
print
Stepbystep Tree Building:"
while lenheap:
# Pop the two smallest nodes
left heapq.heappopheap
right heapq.heappopheap
# Combine these two nodes into a new parent node
merged HuffmanNodeNone left.freq right.freq
merged.left left
merged.right right
# Push the parent node back into the priority queue
heapq.heappushheap merged
printfCombined nodes with frequencies leftfreq and rightfreq into mergedfreq
# The root of the tree
root heap
# Recursively assign codes
codes
def assigncodesnode code:
if node is not None:
if node.char is not None:
codesnodechar code
assigncodesnodeleft, code
assigncodesnoderight, code
assigncodesroot
print
Final Huffman Codes:"
for char, code in codes.items:
printfchar: code
return codes
# Input frequencies
frequencies
a:
b:
c:
d:
e:
f:
g:
h:
i:
j:
# Run the Huffman coding algorithm
codes calculatehuffmancodesfrequencies
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
