-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffline_6_grdy.py.old
99 lines (82 loc) · 2.48 KB
/
offline_6_grdy.py.old
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
import queue
class Node:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
# def traverse(node, key, value, code=""):
# print(node)
# print(type(node))
# print(code)
# code = ""
# if (type(node)==tuple):
# print("test")
# if (node[1]==key):
# return code
# else:
# return
# elif value< node.cargo:
# code+("1")
# traverse(node.left, key, value)
# elif value> node.cargo:
# code+("0")
# traverse(node.right, key, value)
# return code
def traverse(node, prefix="", code={}):
# print(node)
# print(type(node))
print(code)
# print(prefix)
if type(node)!=tuple:
print(node.left)
print((node.left)[1])
if type((node.left)[1])==Node:
traverse(node.left, prefix+"0", code)
else:
code[(node)[1]] = prefix+"0"
if type(node)!=tuple:
print((node.right)[1])
print(node.right)
if type((node.right)[1])==Node:
traverse(node.right, prefix+"1", code)
else:
code[(node)[1]] = prefix+"1"
return code
# if (type(node)==tuple):
# print("test")
# if (node[1]==key):
# return code
# else:
# return
# elif value< node.cargo:
# code+("1")
# traverse(node.left, key, value)
# elif value> node.cargo:
# code+("0")
# traverse(node.right, key, value)
# return code
if __name__ == '__main__':
f = open('offline_6_input.txt')
num_of_tests = int(f.readline())
for _ in range(num_of_tests):
n = int(f.readline())
freq_dic = {}
freq_q = queue.PriorityQueue()
for i in range(n):
line = f.readline().rstrip().split(" ")
freq_dic[line[0]] = int(line[1])
freq_q.put((int(line[1]), line[0]))
while(freq_q.qsize()>1):
left = freq_q.get()
right = freq_q.get()
node = Node(left[0]+right[0], left, right)
freq_q.put((left[0]+right[0], node))
root = (freq_q.get())[1]
print(root.right)
code_dic = traverse(root)
# print(freq_dic)
# for value in sorted(freq_dic, key=freq_dic.get, reverse=False):
# for key, value in freq_dic.items():
# traverse(root, key, value)