-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.py
More file actions
39 lines (36 loc) · 994 Bytes
/
trie.py
File metadata and controls
39 lines (36 loc) · 994 Bytes
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
class Trie:
def __init__(self):
self.root = {}
def insert(self, sequence):
node = self.root
for item in sequence:
if item in node.keys():
node = node[item]
else:
node[item] = {}
node = node[item]
node['end'] = True
def search(self, word):
node = self.root
for w in word:
if w not in node.keys():
return False
else:
node = node[w]
mark = node.get('end')
return mark is not None
def startsWith(self, prefix):
curnode = self.root
for w in prefix:
if w not in curnode.keys():
return False
curnode = curnode[w]
return True
if __name__ == '__main__':
t = Trie()
t.insert('apple')
assert not t.search('app')
assert t.search('apple')
t.insert('app')
assert t.search('app')
assert t.startsWith('app')