Advertisement
Guest User

в

a guest
Nov 28th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import Queue
  2.  
  3. class HuffmanNode(object):
  4.     def __init__(self, left=None, right=None, root=None):
  5.         self.left = left
  6.         self.right = right
  7.         self.root = root     # Why?  Not needed for anything.
  8.     def children(self):
  9.         return((self.left, self.right))
  10.  
  11. '''freq = [
  12.    (8.167, 'a'), (1.492, 'b'), (2.782, 'c'), (4.253, 'd'),
  13.    (12.702, 'e'),(2.228, 'f'), (2.015, 'g'), (6.094, 'h'),
  14.    (6.966, 'i'), (0.153, 'j'), (0.747, 'k'), (4.025, 'l'),
  15.    (2.406, 'm'), (6.749, 'n'), (7.507, 'o'), (1.929, 'p'),
  16.    (0.095, 'q'), (5.987, 'r'), (6.327, 's'), (9.056, 't'),
  17.    (2.758, 'u'), (1.037, 'v'), (2.365, 'w'), (0.150, 'x'),
  18.    (1.974, 'y'), (0.074, 'z') ]'''
  19. #freq = [(0.22, 'z1'), (0.2, 'z2'), (0.16, 'z3'), (0.16, 'z4'), (0.1, 'z5'), (0.1, 'z6'), (0.04, 'z7'), (0.02, 'z8')]
  20. freq = [(0.4, 'a'), (0.3, 'b'), (0.2, 'c'), (0.1, 'd')]
  21. print(len(freq))
  22. for i in range(len(freq)):
  23.     freq[i] = (freq[i][0],freq[i][1],0)
  24.  
  25. def create_tree(frequencies):
  26.     p = Queue.PriorityQueue()
  27.     for value in frequencies:    # 1. Create a leaf node for each symbol
  28.         p.put(value)             #    and add it to the priority queue
  29.     while p.qsize() > 1:         # 2. While there is more than one node
  30.         l, r = p.get(), p.get()  # 2a. remove two highest nodes
  31.         if(l[0]>=r[0]):
  32.             l =(l[0],l[1],1)
  33.         else:
  34.             r =(r[0],r[1],1)
  35.         node = HuffmanNode(l, r) # 2b. create internal node with children
  36.         p.put((l[0]+r[0], node, 0)) # 2c. add new node to queue
  37.     return p.get()               # 3. tree is complete - return root node
  38.  
  39. node = create_tree(freq)
  40. print(node)
  41.  
  42. # Recursively walk the tree down to the leaves,
  43. #   assigning a code value to each symbol
  44.  
  45. for i in sorted(freq, reverse=True):
  46.     print(i[1],i[0]) #'{:6.2f}'.format(i[0]), code[i[1]])
  47.  
  48. print(tuple==node.__class__)
  49. code = []
  50. def Obhad(node):
  51.     if node[1].__class__ == str:
  52.         code.append(str(node[2]))
  53.         print (node[1], (''.join(code)))
  54.         code.pop()
  55.         return
  56.     (left, right) = node[1].children()
  57.     code.append(str(node[2]))
  58.     print((''.join(code)))
  59.     Obhad(left)
  60.     Obhad(right)
  61. Obhad(node)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement