forked from adityabisoi/ds-algo-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
103 lines (77 loc) · 2.23 KB
/
solution.py
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
import queue as Queue
cntr = 0
class Node:
def __init__(self, freq, data):
self.freq = freq
self.data = data
self.left = None
self.right = None
global cntr
self._count = cntr
cntr = cntr + 1
def __lt__(self, other):
if self.freq != other.freq:
return self.freq < other.freq
return self._count < other._count
def huffman_hidden():#builds the tree and returns root
q = Queue.PriorityQueue()
for key in freq:
q.put((freq[key], key, Node(freq[key], key) ))
while q.qsize() != 1:
a = q.get()
b = q.get()
obj = Node(a[0] + b[0], '\0' )
obj.left = a[2]
obj.right = b[2]
q.put((obj.freq, obj.data, obj ))
root = q.get()
root = root[2]#contains root object
return root
def dfs_hidden(obj, already):
if(obj == None):
return
elif(obj.data != '\0'):
code_hidden[obj.data] = already
dfs_hidden(obj.right, already + "1")
dfs_hidden(obj.left, already + "0")
"""class Node:
def __init__(self, freq,data):
self.freq= freq
self.data=data
self.left = None
self.right = None
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
def decodeHuff(root, s):
#Enter Your Code Here
# create temporary pointer
temp = root
result = []
# traverse binary coded string
for char in s:
# traverse to left
if char is '0':
temp = temp.left
# traverse to right
else:
temp = temp.right
# check for leaf node
if temp.left is None and temp.right is None:
result.append(temp.data)
temp = root
print("".join(result))
ip = input()
freq = {}#maps each character to its frequency
cntr = 0
for ch in ip:
if(freq.get(ch) == None):
freq[ch] = 1
else:
freq[ch]+=1
root = huffman_hidden()#contains root of huffman tree
code_hidden = {}#contains code for each object
dfs_hidden(root, "")
if len(code_hidden) == 1:#if there is only one character in the i/p
for key in code_hidden:
code_hidden[key] = "0"
toBeDecoded = ""