-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffman_coding.py
More file actions
399 lines (264 loc) · 13.9 KB
/
Copy pathhuffman_coding.py
File metadata and controls
399 lines (264 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 2 03:57:24 2020
@author: JAGRUTI
"""
import sys
# defining Node class for the tree
class Node(object):
def __init__(self, value=None, char=None, binary_code=None):
self.value = value
self.char = char
self.left = None
self.right = None
# defining minHeap for priority queue implementation - O(log(n)) - insertion and deletion
class minHeap(object):
def __init__(self):
self.arr = []
# for adding a node to priority queue
def push(self, Node=None):
self.arr.append(Node)
# if it is not the first node
if len(self.arr) > 1:
child_index = len(self.arr)-1
parent_index = (child_index-1) // 2
# compare until the child is smaller than the parent or child becomes the root element means at the top
while(parent_index>=0 and self.arr[child_index].value<self.arr[parent_index].value):
# swap the values
temp = self.arr[child_index]
self.arr[child_index] = self.arr[parent_index]
self.arr[parent_index] = temp
# repeat the procedure at the parent node
child_index = parent_index
parent_index = (child_index-1) // 2
# removing the top element from the minHeap
def pop(self):
if len(self.arr) == 0:
return
node = self.arr[0] # the top element is the minimum
self.arr[0] = self.arr[-1] # get the last element at the first
self.arr.pop() # decrease the array size by '1' from the right side of the array
# downheapify to set the top element at the correct position
parent_index = 0
while(parent_index<len(self.arr)):
# find the minimum of the parent node and its two child nodes
left_child_index = 2*parent_index + 1
right_child_index = 2*parent_index + 2
minimum = self.arr[parent_index]
# if left child exists
if left_child_index < len(self.arr):
if self.arr[left_child_index].value<minimum.value:
minimum = self.arr[left_child_index]
# if right child exists
if right_child_index < len(self.arr):
if self.arr[right_child_index].value<minimum.value:
minimum = self.arr[right_child_index]
# if parent is the minimum, means it is at the correct position, hence come out of the loop
if minimum == self.arr[parent_index]:
break
# if left child is minimum, swap parent and left child values and continue the process for the left child node
elif minimum == self.arr[left_child_index]:
self.arr[left_child_index] = self.arr[parent_index]
self.arr[parent_index] = minimum
parent_index = left_child_index
# if right child is minimum, swap parent and right child values and continue the process for the right child node
else:
self.arr[right_child_index] = self.arr[parent_index]
self.arr[parent_index] = minimum
parent_index = right_child_index
return node
def huffman_encoding(data):
if len(data) is 0:
print("Error! Enter some data:")
return "", None
# storing character and frequency as key, value pair
dict_char = {}
for char in data:
if char not in dict_char:
dict_char[char] = 1
else:
dict_char[char] += 1
# creating the minHeap
minHeap1 = minHeap()
# adding elements to minHeap
for char, frequency in dict_char.items():
# each node contains the character and it's frequency
newNode = Node(frequency, char)
minHeap1.push(newNode)
# building the huffman tree
while(len(minHeap1.arr)>1):
# remove the two minimum elements from the minHeap
element1 = minHeap1.pop()
element2 = minHeap1.pop()
# add their values
sum_elements = element1.value + element2.value
# make a new node with the sum
parent = Node(sum_elements)
# make the smaller value node as left child and larger one as right child
parent.left = element1
parent.right = element2
# add the sum node to minHeap
minHeap1.push(parent)
# root of the huffman tree
root = minHeap1.pop()
#pre_order_traversal(root)
# create encoding for each character
huff_char = create_code(root)
# encode the string by using the encoding
encoding = ""
if huff_char:
for char in data:
encoding += huff_char[char]
# this happens when the string contains only one character
else:
encoding = "0"
return encoding, root
# create encoding for each character
def create_code(node, code=''):
# code list
list_of_codes = {}
# if huffman tree has just one node ,i.e, the root
if node.left == None and node.right == None:
return list_of_codes
# add a '0' for the left child
code_left = code + '0'
# if left child has a character, it is a leaf node, hence add the obtained code for that character
if node.left.char:
list_of_codes[node.left.char] = code_left
# else traverse the left child
else:
list_of_codes = create_code(node.left, code_left)
# add a '1' for the right child
code_right = code + '1'
# if right child has a character, it is a leaf node, hence add the obtained code for that character
if node.right.char:
list_of_codes[node.right.char] = code_right
# else traverse the right child
else:
list_of_codes.update(create_code(node.right, code_right))
return list_of_codes
# for pre-order traversal of tree
def pre_order_traversal(node):
if node is None:
return
print("Character: {}, Value:{}".format(node.char, node.value))
pre_order_traversal(node.left)
pre_order_traversal(node.right)
# for decoding the encoded string
def huffman_decoding(data, tree):
# if the encoding has a single value, it means the string has just one character with frequency:tree.value"
if len(data) == 1:
word = "".join(tree.char for i in range(tree.value))
return word
# start from the huffman tree root
node = tree
index = 0
decoded_data = ""
while(index<len(data)):
# if '0' is there traverse left
if data[index] == '0':
node = node.left
# if '1' is there traverse right
elif data[index] == '1':
node = node.right
# if node has a character, it means, leaf node is reached
# and hence add the character at the leaf of tree to the decoded data
if node.char:
decoded_data += node.char
node = tree
# increment the index
index += 1
return decoded_data
## Test Cases
if __name__ == "__main__":
list_of_strings = ["AAAAAAABBBCCCCCCCDDEEEEEE", "The bird is the word", "a", "aa", "ab", "~!@#$%^&*()_+`1234567890-={}[]|\:;<>,.?/",
"Topic sentences are similar to mini thesis statements! Like a thesis statement, a topic sentence has a specific main point. Whereas the thesis is the main point of the essay, the topic sentence is the main point of the paragraph. Like the thesis statement, a topic sentence has a unifying function. But a thesis statement or topic sentence alone doesn’t guarantee unity. An essay is unified if all the paragraphs relate to the thesis, whereas a paragraph is unified if all the sentences relate to the topic sentence. Note: Not all paragraphs need topic sentences. In particular, opening and closing paragraphs, which serve different functions from body paragraphs, generally don’t have topic sentences?"
,"bbbbbbbbbbbbbbb", ""]
for index, string in enumerate(list_of_strings):
print("Example: {}\n".format(index+1))
print ("The size of the data is: {}\n".format(sys.getsizeof(string)))
print ("The content of the data is: {}\n".format(string))
encoded_data, tree = huffman_encoding(string)
if tree:
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
#print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the decoded data is: {}\n".format(decoded_data))
if string == decoded_data:
print("string: {} properly encoded and decoded".format(index + 1))
else:
print("string: {} not properly encoded and decoded".format(index + 1))
print("\n--------------------------------------------------------------------------------\n")
## Outputs:
"""
Example: 1
The size of the data is: 74
The content of the data is: AAAAAAABBBCCCCCCCDDEEEEEE
The size of the encoded data is: 32
The size of the decoded data is: 74
The content of the decoded data is: AAAAAAABBBCCCCCCCDDEEEEEE
string: 1 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 2
The size of the data is: 69
The content of the data is: The bird is the word
The size of the encoded data is: 36
The size of the decoded data is: 69
The content of the decoded data is: The bird is the word
string: 2 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 3
The size of the data is: 50
The content of the data is: a
The size of the encoded data is: 24
The size of the decoded data is: 50
The content of the decoded data is: a
string: 3 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 4
The size of the data is: 51
The content of the data is: aa
The size of the encoded data is: 24
The size of the decoded data is: 51
The content of the decoded data is: aa
string: 4 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 5
The size of the data is: 51
The content of the data is: ab
The size of the encoded data is: 28
The size of the decoded data is: 51
The content of the decoded data is: ab
string: 5 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 6
The size of the data is: 89
The content of the data is: ~!@#$%^&*()_+`1234567890-={}[]|\:;<>,.?/
The size of the encoded data is: 56
The size of the decoded data is: 89
The content of the decoded data is: ~!@#$%^&*()_+`1234567890-={}[]|\:;<>,.?/
string: 6 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 7
The size of the data is: 1478
The content of the data is: Topic sentences are similar to mini thesis statements! Like a thesis statement, a topic sentence has a specific main point. Whereas the thesis is the main point of the essay, the topic sentence is the main point of the paragraph. Like the thesis statement, a topic sentence has a unifying function. But a thesis statement or topic sentence alone doesn’t guarantee unity. An essay is unified if all the paragraphs relate to the thesis, whereas a paragraph is unified if all the sentences relate to the topic sentence. Note: Not all paragraphs need topic sentences. In particular, opening and closing paragraphs, which serve different functions from body paragraphs, generally don’t have topic sentences?
The size of the encoded data is: 412
The size of the decoded data is: 1478
The content of the decoded data is: Topic sentences are similar to mini thesis statements! Like a thesis statement, a topic sentence has a specific main point. Whereas the thesis is the main point of the essay, the topic sentence is the main point of the paragraph. Like the thesis statement, a topic sentence has a unifying function. But a thesis statement or topic sentence alone doesn’t guarantee unity. An essay is unified if all the paragraphs relate to the thesis, whereas a paragraph is unified if all the sentences relate to the topic sentence. Note: Not all paragraphs need topic sentences. In particular, opening and closing paragraphs, which serve different functions from body paragraphs, generally don’t have topic sentences?
string: 7 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 8
The size of the data is: 64
The content of the data is: bbbbbbbbbbbbbbb
The size of the encoded data is: 24
The size of the decoded data is: 64
The content of the decoded data is: bbbbbbbbbbbbbbb
string: 8 properly encoded and decoded
--------------------------------------------------------------------------------
Example: 9
The size of the data is: 49
The content of the data is:
Error! Enter some data:
--------------------------------------------------------------------------------
"""