From cad82760d7417ba0fe92ac2ea46ce94a12b03d3c Mon Sep 17 00:00:00 2001 From: Saloni Shah Date: Thu, 1 Oct 2020 09:18:42 +0530 Subject: [PATCH 1/2] Add files via upload --- algorithms/greedy/Huffman_Coding.py | 60 +++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 algorithms/greedy/Huffman_Coding.py diff --git a/algorithms/greedy/Huffman_Coding.py b/algorithms/greedy/Huffman_Coding.py new file mode 100644 index 00000000..481a17cf --- /dev/null +++ b/algorithms/greedy/Huffman_Coding.py @@ -0,0 +1,60 @@ +# Huffman Coding in python + +string = 'BCAADDDCCACACAC' + + +# Creating tree nodes +class NodeTree(object): + + def __init__(self, left=None, right=None): + self.left = left + self.right = right + + def children(self): + return (self.left, self.right) + + def nodes(self): + return (self.left, self.right) + + def __str__(self): + return '%s_%s' % (self.left, self.right) + + +# Main function implementing huffman coding +def huffman_code_tree(node, left=True, binString=''): + if type(node) is str: + return {node: binString} + (l, r) = node.children() + d = dict() + d.update(huffman_code_tree(l, True, binString + '0')) + d.update(huffman_code_tree(r, False, binString + '1')) + return d + + +# Calculating frequency +freq = {} +for c in string: + if c in freq: + freq[c] += 1 + else: + freq[c] = 1 + +freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) + +nodes = freq + +while len(nodes) > 1: + (key1, c1) = nodes[-1] + (key2, c2) = nodes[-2] + nodes = nodes[:-2] + node = NodeTree(key1, key2) + nodes.append((node, c1 + c2)) + + nodes = sorted(nodes, key=lambda x: x[1], reverse=True) + +huffmanCode = huffman_code_tree(nodes[0][0]) + +print(' Char | Huffman code ') +print('----------------------') +for (char, frequency) in freq: + print(' %-4r |%12s' % (char, huffmanCode[char])) \ No newline at end of file From b1f2f3da88602abb2cf5dbfec4205ae86e123470 Mon Sep 17 00:00:00 2001 From: Saloni Shah Date: Thu, 1 Oct 2020 09:24:33 +0530 Subject: [PATCH 2/2] Update Huffman_Coding.py --- algorithms/greedy/Huffman_Coding.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/greedy/Huffman_Coding.py b/algorithms/greedy/Huffman_Coding.py index 481a17cf..d80124ed 100644 --- a/algorithms/greedy/Huffman_Coding.py +++ b/algorithms/greedy/Huffman_Coding.py @@ -57,4 +57,4 @@ def huffman_code_tree(node, left=True, binString=''): print(' Char | Huffman code ') print('----------------------') for (char, frequency) in freq: - print(' %-4r |%12s' % (char, huffmanCode[char])) \ No newline at end of file + print(' %-4r |%12s' % (char, huffmanCode[char]))