Skip to content

Commit 10befec

Browse files
authored
Create Huffman_Coding.py
Python implementation of Huffman Coding using Greedy Approach
1 parent 9b05b2e commit 10befec

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

algorithms/Huffman_Coding.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
string = 'BCAADDDCCACACAC'
2+
3+
4+
# Creating tree nodes
5+
class NodeTree(object):
6+
7+
def __init__(self, left=None, right=None):
8+
self.left = left
9+
self.right = right
10+
11+
def children(self):
12+
return (self.left, self.right)
13+
14+
def nodes(self):
15+
return (self.left, self.right)
16+
17+
def __str__(self):
18+
return '%s_%s' % (self.left, self.right)
19+
20+
21+
# Main function implementing huffman coding
22+
def huffman_code_tree(node, left=True, binString=''):
23+
if type(node) is str:
24+
return {node: binString}
25+
(l, r) = node.children()
26+
d = dict()
27+
d.update(huffman_code_tree(l, True, binString + '0'))
28+
d.update(huffman_code_tree(r, False, binString + '1'))
29+
return d
30+
31+
32+
# Calculating frequency
33+
freq = {}
34+
for c in string:
35+
if c in freq:
36+
freq[c] += 1
37+
else:
38+
freq[c] = 1
39+
40+
freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
41+
42+
nodes = freq
43+
44+
while len(nodes) > 1:
45+
(key1, c1) = nodes[-1]
46+
(key2, c2) = nodes[-2]
47+
nodes = nodes[:-2]
48+
node = NodeTree(key1, key2)
49+
nodes.append((node, c1 + c2))
50+
51+
nodes = sorted(nodes, key=lambda x: x[1], reverse=True)
52+
53+
huffmanCode = huffman_code_tree(nodes[0][0])
54+
55+
print(' Char | Huffman code ')
56+
print('----------------------')
57+
for (char, frequency) in freq:
58+
print(' %-4r |%12s' % (char, huffmanCode[char]))

0 commit comments

Comments
 (0)