Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import heapq
  2. class Node:
  3.     def __init__(self, ch, fr):
  4.         self.char = ch
  5.         self.freq = fr
  6.         self.left = None
  7.         self.right = None
  8.  
  9.     def __lt__(self, other):
  10.         return self.freq < other.freq
  11.  
  12. class HuffmanCode:
  13.     #HashMap to store the bits of every character
  14.     codes = {}
  15.     '''
  16.        None is equivalent to Null
  17.    '''
  18.     def encode(self, root, text):
  19.         if root is None:
  20.             return
  21.  
  22.         if root.left is None and root.right is None:
  23.             self.codes[root.char] = text
  24.             return
  25.  
  26.         self.encode(root.right, text + "1")
  27.         self.encode(root.left, text + "0")
  28.  
  29.  
  30.     def decode(self, root, bitString):
  31.         print(bitString)
  32.         curr = root
  33.         decodeString = ""
  34.         for bit in bitString:
  35.             if curr is None:
  36.                 return
  37.  
  38.             if bit == '1':
  39.                 curr = curr.right
  40.             else:
  41.                 curr = curr.left
  42.  
  43.             if curr.left is None and curr.right is None:
  44.                 decodeString += curr.char
  45.                 curr = root
  46.  
  47.         print(decodeString)
  48.  
  49.     def buildTree(self, textString):
  50.         queue = []
  51.         #HashMap
  52.         map = {}
  53.  
  54.         #Loop through the text and increment the frequnency
  55.         for c in textString:
  56.             if not c in map:
  57.                 map[c] = 1
  58.             else:
  59.                 map[c] += 1
  60.  
  61.         #Loop through the map and create leaves
  62.         for key in map:
  63.             heapq.heappush(queue, Node(key, map[key]))
  64.  
  65.         #Loop through the queue and build the tree
  66.         while len(queue) > 1:
  67.             node1 = heapq.heappop(queue)
  68.             node2 = heapq.heappop(queue)
  69.  
  70.             newNode = Node(None, node1.freq + node2.freq)
  71.  
  72.             newNode.left = node1
  73.             newNode.right = node2
  74.  
  75.             heapq.heappush(queue, newNode)
  76.  
  77.         root = heapq.heappop(queue)
  78.         text = ""
  79.         self.encode(root, text)
  80.         for key in self.codes:
  81.             print(key, self.codes[key])
  82.  
  83.         tempString = ""
  84.         for c in textString:
  85.             tempString += self.codes[c]
  86.  
  87.  
  88.         self.decode(root, tempString)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement