-
Notifications
You must be signed in to change notification settings - Fork 0
/
ternarySearchTree.py
208 lines (147 loc) · 5.23 KB
/
ternarySearchTree.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
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
class Node:
def __init__(self, data=None, rating=None, payload=None):
self.data = data
self.rating = rating
self.payload = payload
self.left = None
self.right = None
self.eq = None
def __str__(self):
return '<Node[{0}][{1}]'.format(self.data, self.rating)
def __repr__(self):
return self.__str__()
class TernarySearchTree:
def __init__(self):
self.root = Node()
self._count_leaves = 0
self._cache = {}
def __str__(self):
return '<TernarySearchTree: {0} words>'.format(self._count_leaves)
def __repr__(self):
return self.__str__()
def __contains__(self, item):
child = self.search(item)
if child is not None:
return child.rating is not None
else:
return False
def __len__(self):
return self._count_leaves
def _insert(self, node, char, rating=None, payload=None):
if node.data is None:
node.data = char
if rating is None:
node.eq = Node()
return node.eq
# When rating is not None -> last char in inserting word
else:
# When inserting value which is already in tree nothing
# happen
if node.rating is None:
node.rating = rating
node.payload = payload
self._count_leaves += 1
return None
if char == node.data:
# middle
if node.eq is None:
node.eq = Node()
return node.eq
elif char > node.data:
# right
if node.right is None:
node.right = Node()
return self._insert(node.right, char, rating)
else:
# left
if node.left is None:
node.left = Node()
return self._insert(node.left, char, rating)
def _search(self, node, char, end=False):
if node is None or node.data is None:
return None
if node.data == char:
if not end:
return node.eq
else:
return node
elif char > node.data:
return self._search(node.right, char, end)
else:
return self._search(node.left, char, end)
def _traverse(self, node, prefix, buffer, full_traverse=True):
if full_traverse:
leaves = (node.left, node.eq, node.right)
else:
leaves = (None, node.eq, None)
for i in range(3):
if leaves[i] is not None:
if i == 1:
self._traverse(leaves[i], prefix + node.data, buffer)
else:
self._traverse(leaves[i], prefix, buffer)
if node.rating is not None:
buffer.append((node.rating, prefix + node.data, node.payload))
def _prefixes(self, string):
res = []
while string:
res.append(string)
string = string[:len(string) - 1]
return res
def optimize(self, common_num=10, cache_threshold=1000):
prefixes = set([])
for _, word in self.common_prefix(
'', limit=self._count_leaves, with_payload=False):
prefixes.update(self._prefixes(word))
prefixes.add('')
for prefix in prefixes:
leaves = self.common_prefix(prefix, limit=self._count_leaves)
if len(leaves) >= cache_threshold:
self._cache[prefix] = sorted(
leaves, key=lambda it: it[0], reverse=True)[:common_num]
def insert(self, string, rating, payload=None):
node = self.root
lstring = len(string)
for i in range(lstring):
# If this is the last letter -> pass rating
if i == lstring - 1:
self._insert(node, string[i], rating, payload)
else:
node = self._insert(node, string[i])
def search(self, string):
node = self.root
lstring = len(string)
for i in range(lstring):
if i == lstring - 1:
node = self._search(node, string[i], True)
else:
node = self._search(node, string[i])
if node is None:
return None
return node
def common_prefix(self, prefix, limit=10, with_payload=True):
if prefix in self._cache:
return self._cache[prefix][:limit]
if prefix == '':
child = self.root
full_traverse = True
else:
child = self.search(prefix)
full_traverse = False
# Nothing found
if child is None:
return []
buffer = []
self._traverse(child, prefix[0:-1], buffer, full_traverse)
buffer.sort(key=lambda it: it[0], reverse=True)
buffer = buffer[:limit]
if not with_payload:
buffer = [(it[0], it[1]) for it in buffer]
return buffer
def get(self, item, with_payload=False):
child = self.search(item)
if child is not None:
if with_payload:
return child.rating, child.payload
else:
return child.rating