-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
51 lines (43 loc) · 1.27 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
class Trie:
def __init__(self):
self.children = {}
self.end_of_word = 0
self.word = ''
def __repr__(self):
return f'{self.word} {self.end_of_word}'
def __str__(self):
return self.__repr__()
def put(self, word: str, cnt=1):
node = self
for char in word:
child = node.children.get(char)
if child:
node = child
else:
new_node = Trie()
node.children[char] = new_node
node = new_node
node.end_of_word += int(cnt)
node.word = word
def get(self, prefix: str):
node = self
if not node.children:
return 0
for char in prefix:
child = node.children.get(char)
if child:
node = child
else:
return 0
words = []
if node.end_of_word:
words.append(node)
Trie.get_words(node, words)
words = sorted(words, key=lambda x: x.end_of_word, reverse=True)
return words
@staticmethod
def get_words(node, words):
for child in node.children.values():
if child.end_of_word:
words.append(child)
Trie.get_words(child, words)