-
Notifications
You must be signed in to change notification settings - Fork 312
/
Trie.py
27 lines (24 loc) · 810 Bytes
/
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
class Trie:
def __init__(self, *words):
self.root = {}
for word in words:
self.add(word)
def add(self, word):
current_dict = self.root
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict["_end_"] = True
def __contains__(self, word):
current_dict = self.root
for letter in word:
if letter not in current_dict:
return False
current_dict = current_dict[letter]
return "_end_" in current_dict
def __delitem__(self, word):
current_dict = self.root
nodes = [current_dict]
for letter in word:
current_dict = current_dict[letter]
nodes.append(current_dict)
del current_dict["_end_"]