forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.py
43 lines (38 loc) · 1.15 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
class node:
def __init__(self):
self.children = dict()
class trie:
def __init__(self):
self.root = node()
def add_word(self, word):
current = self.root
for letter in word:
if letter not in current.children:
current.children[letter] = node()
current = current.children[letter]
return self
def remove_word(self, word):
current = self.root
for letter in word:
if letter in current.children and len(current.children)==1:
del current.children[letter]
return self
def search(self, word):
current = self.root
for letter in word:
if letter not in current.children:
return False
current = current.children[letter]
return True
def main():
t = trie()
t.add_word('mississippi')
t.add_word('miss')
t.add_word('michigan')
t.add_word('missouri')
t.remove_word('missouri')
assert t.search('mississippi')
assert t.search('missi')
assert not t.search('mint')
assert not t.search('missouri')
assert not t.search('mississippi!')