Advertisement
paulogp

Huffman

Aug 7th, 2011
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # paulogp
  3. # http://en.literateprograms.org/Huffman_coding_(Python)
  4.  
  5. def makeHuffTree(symbolTupleList):
  6.     sortedList = list(symbolTupleList)
  7.     sortedList.sort()
  8.  
  9.     from bisect import insort
  10.  
  11.     while len(sortedList) > 1:
  12.         childL, childR = sortedList.pop(1), sortedList.pop(0)
  13.         parent = (childL[0] + childR[0], childL, childR)
  14.         insort(sortedList, parent)
  15.  
  16.     return sortedList[0]
  17.  
  18. def printHuffTree(huffTree, prefix = ''):
  19.     if len(huffTree) == 2:
  20.         print huffTree[1], prefix
  21.     else:
  22.         printHuffTree(huffTree[1], prefix + '0')
  23.         printHuffTree(huffTree[2], prefix + '1')
  24.  
  25. # Exemplo
  26. exampleData = [
  27.     (0.124167  , 'e'),
  28.     (0.0969225 , 't'),
  29.     (0.0820011 , 'a'),
  30.     (0.0768052 , 'i'),
  31.     (0.0764055 , 'n'),
  32.     (0.0714095 , 'o'),
  33.     (0.0706768 , 's'),
  34.     (0.0668132 , 'r'),
  35.     (0.0448308 , 'l'),
  36.     (0.0363709 , 'd'),
  37.     (0.0350386 , 'h'),
  38.     (0.0344391 , 'c'),
  39.     (0.028777  , 'u'),
  40.     (0.0281775 , 'm'),
  41.     (0.0235145 , 'f'),
  42.     (0.0203171 , 'p'),
  43.     (0.0189182 , 'y'),
  44.     (0.0181188 , 'g'),
  45.     (0.0135225 , 'w'),
  46.     (0.0124567 , 'v'),
  47.     (0.0106581 , 'b'),
  48.     (0.00393019, 'k'),
  49.     (0.00219824, 'x'),
  50.     (0.0019984 , 'j'),
  51.     (0.0009325 , 'q'),
  52.     (0.000599  , 'z')
  53. ]
  54.  
  55. if __name__ == '__main__':
  56.     huffTree = makeHuffTree(exampleData)
  57.     printHuffTree(huffTree)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement