-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
55 lines (44 loc) · 1.58 KB
/
trie.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
import pickle
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word, page_num, position):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
if "positions" not in node.children:
node.children["positions"] = []
node.children["positions"].append((page_num, position))
node.is_end_of_word = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return []
node = node.children[char]
return node.children.get("positions")
def starts_with(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
words_with_positions = []
self._dfs(node, prefix, words_with_positions)
return words_with_positions
def _dfs(self, node, prefix, words_with_positions):
if node.is_end_of_word:
words_with_positions.append((prefix, node.children.get("positions", [])))
for char, next_node in node.children.items():
if char != "positions":
self._dfs(next_node, prefix + char, words_with_positions)
def serialize(data):
return pickle.dumps(data)
def deserialize(data):
return pickle.loads(data)