Advertisement
amu2002

HuffmanCoding

Nov 20th, 2023
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. string = input('Enter the string: ')
  2.  
  3. class NodeTree(object):
  4.     def __init__(self, left=None, right=None):
  5.         self.left = left
  6.         self.right = right
  7.  
  8.     def children(self):
  9.         return (self.left, self.right)
  10.  
  11.     def nodes(self):
  12.         return (self.left, self.right)
  13.  
  14.     def __str__(self):
  15.         return '%s_%s' % (self.left, self.right)
  16.  
  17. def huffman_code_tree(node, left=True, binString=''):
  18.     if type(node) is str:
  19.         return {node: binString}
  20.  
  21.     (l, r) = node.children()
  22.     d = dict()
  23.     d.update(huffman_code_tree(l, True, binString + '0'))
  24.     d.update(huffman_code_tree(r, False, binString + '1'))
  25.     return d
  26.  
  27. freq = {}
  28. for c in string:
  29.     if c in freq:
  30.         freq[c] += 1
  31.     else:
  32.         freq[c] = 1
  33.  
  34. freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
  35. nodes = [(key, freq) for key, freq in freq]
  36. while len(nodes) > 1:
  37.     (key1, c1) = nodes[-1]
  38.     (key2, c2) = nodes[-2]
  39.     nodes = nodes[:-2]
  40.     node = NodeTree(key1, key2)
  41.     nodes.append((node, c1 + c2))
  42.     nodes = sorted(nodes, key=lambda x: x[1], reverse=True)
  43.  
  44. huffmanCode = huffman_code_tree(nodes[0][0])
  45. print(' Char | Huffman code ')
  46. print('----------------------')
  47. for (char, frequency) in freq:
  48.     print(' %-4r |%12s' % (char, huffmanCode[char]))
  49.  
  50. """ Enter the string: acdbfe
  51.    Char | Huffman code
  52.    ----------------------
  53.    'a'  |         101
  54.    'c'  |         100
  55.    'd'  |         111
  56.    'b'  |         110
  57.    'f'  |          01
  58.    'e'  |          00
  59. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement