Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Queue
- class HuffmanNode(object):
- def __init__(self, left=None, right=None, root=None):
- self.left = left
- self.right = right
- self.root = root # Why? Not needed for anything.
- def children(self):
- return((self.left, self.right))
- '''freq = [
- (8.167, 'a'), (1.492, 'b'), (2.782, 'c'), (4.253, 'd'),
- (12.702, 'e'),(2.228, 'f'), (2.015, 'g'), (6.094, 'h'),
- (6.966, 'i'), (0.153, 'j'), (0.747, 'k'), (4.025, 'l'),
- (2.406, 'm'), (6.749, 'n'), (7.507, 'o'), (1.929, 'p'),
- (0.095, 'q'), (5.987, 'r'), (6.327, 's'), (9.056, 't'),
- (2.758, 'u'), (1.037, 'v'), (2.365, 'w'), (0.150, 'x'),
- (1.974, 'y'), (0.074, 'z') ]'''
- #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')]
- freq = [(0.4, 'a'), (0.3, 'b'), (0.2, 'c'), (0.1, 'd')]
- print(len(freq))
- for i in range(len(freq)):
- freq[i] = (freq[i][0],freq[i][1],0)
- def create_tree(frequencies):
- p = Queue.PriorityQueue()
- for value in frequencies: # 1. Create a leaf node for each symbol
- p.put(value) # and add it to the priority queue
- while p.qsize() > 1: # 2. While there is more than one node
- l, r = p.get(), p.get() # 2a. remove two highest nodes
- if(l[0]>=r[0]):
- l =(l[0],l[1],1)
- else:
- r =(r[0],r[1],1)
- node = HuffmanNode(l, r) # 2b. create internal node with children
- p.put((l[0]+r[0], node, 0)) # 2c. add new node to queue
- return p.get() # 3. tree is complete - return root node
- node = create_tree(freq)
- print(node)
- # Recursively walk the tree down to the leaves,
- # assigning a code value to each symbol
- for i in sorted(freq, reverse=True):
- print(i[1],i[0]) #'{:6.2f}'.format(i[0]), code[i[1]])
- print(tuple==node.__class__)
- code = []
- def Obhad(node):
- if node[1].__class__ == str:
- code.append(str(node[2]))
- print (node[1], (''.join(code)))
- code.pop()
- return
- (left, right) = node[1].children()
- code.append(str(node[2]))
- print((''.join(code)))
- Obhad(left)
- Obhad(right)
- Obhad(node)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement