Guest User

Untitled

a guest
Nov 19th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. import heapq
  2. from collections import Counter
  3. from collections import namedtuple
  4.  
  5. class Node(namedtuple("Node", ["left", "right"])):
  6. def walk(self, code, acc):
  7. self.left.walk(code, acc + "0")
  8. self.right.walk(code, acc + "1")
  9.  
  10. class Leaf(namedtuple("Leaf", ["char"])):
  11. def walk(self, code, acc):
  12.  
  13. code[self.char] = acc or "0"
  14.  
  15. def huffman_encode(s):
  16. h = []
  17. for ch, freq in Counter(s).items():
  18. h.append((freq, len(h), Leaf(ch)))
  19. heapq.heapify(h)
  20. count = len(h)
  21. while len(h) > 1:
  22. freq1, _count1, left = heapq.heappop(h)
  23. freq2, _count2, right = heapq.heappop(h)
  24.  
  25. heapq.heappush(h, (freq1 + freq2, count, Node(left, right)))
  26.  
  27. count += 1
  28. code = {}
  29. if h:
  30. [(_freq, _count, root)] = h
  31. root.walk(code, "")
  32. return code
  33.  
  34. import pickle
  35.  
  36. s = open('encoded8bit.bin','r')
  37. code = huffman_encode(s)
  38. encoded = "".join(code[ch] for ch in s)
  39. b = open('56.bin', 'wb')
  40. pickle.dump(encoded, b)
  41. b.close()
  42.  
  43. code = huffman_encode(s)
Add Comment
Please, Sign In to add comment