-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.py
49 lines (43 loc) · 1.47 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
#NEEDED FOR THE TRIE
from functools import reduce
class Trie(object):
# https://github.com/vivekn/autocomplete/blob/master/trie.py#L11
def __init__(self):
self.children = {}
self.flag = False # Flag to represent that a word ends at this node
def add(self, char):
self.children[char] = Trie()
def insert(self, word):
node = self
for char in word:
if char not in node.children:
node.add(char)
node = node.children[char]
node.flag = True
def contains(self, word):
node = self
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.flag
def all_suffixes(self, prefix):
results = set()
if self.flag:
results.add(prefix)
if not self.children: return results
return reduce(lambda a, b: a | b, [node.all_suffixes(prefix + char) for (char, node) in self.children.items()]) | results
def autocomplete(self, prefix):
node = self
for char in prefix:
if char not in node.children:
return set()
node = node.children[char]
return list(node.all_suffixes(prefix))
def one_autocomplete(self,prefix):
node = self
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True