CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

CoCalc’s goal is to provide the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual use to large groups and classes.

| Download
Project: MAT 2540
Views: 74
Visibility: Unlisted (only visible to those who know the link)
Image: ubuntu2004
Kernel: SageMath 8.6

Huffman Code

class binaryTreeNode(): def __init__(self,data=None): self.data = data self.left = None self.right = None def returnData(self): return self.data def printBinaryTree(self,s = '---'): if self.data: print(s+self.data) s = ' ' + s if self.left: self.left.printBinaryTree(s) if self.right: self.right.printBinaryTree(s) def huffmanCode(dictionary): current_nodes = sorted([[binaryTreeNode(item[0]),item[1]] for item in dictionary.items()],key=lambda x: x[1]) while len(current_nodes) > 1: newNode = binaryTreeNode(current_nodes[0][0].data+current_nodes[1][0].data) newNode.left = current_nodes[1][0] newNode.right = current_nodes[0][0] newSum = current_nodes[0][1] + current_nodes[1][1] current_nodes = sorted([[newNode,newSum]] + current_nodes[2:],key=lambda x: x[1]) return current_nodes[0][0] def convertToBinary(tree,c,string=''): if tree.left == None and tree.right == None: return c+': '+string else: if c in tree.left.data: return convertToBinary(tree.left,c,string+'0') else: return convertToBinary(tree.right,c,string+'1')
d = {'A':0.08,'B':0.1,'C':0.12,'D':0.15,'E':0.20,'F':0.35}
huff = huffmanCode(d)
huff.printBinaryTree()
---ABECDF ---CDF ---F ---CD ---D ---C ---ABE ---E ---AB ---B ---A
for key in sorted(d.keys()): print(convertToBinary(huff,key))
A: 111 B: 110 C: 011 D: 010 E: 10 F: 00