forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.py
47 lines (41 loc) · 1.24 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
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 _listify(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 _listify(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 _listify(word):
if letter not in current.children:
return False
current = current.children[letter]
return True
def _listify(self, word):
assert type(word) is int and word > 0
return map(int, list(str(word)))
def main():
t = trie()
t.add_word(123)
t.add_word(1234)
t.add_word(1211111111)
t.add_word(1243)
t.remove_word(1243)
assert t.search(123)
assert t.search(1211111)
assert not t.search(2)
assert not t.search(1243)
assert not t.search(12345)