-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.py
More file actions
59 lines (46 loc) · 1.5 KB
/
Copy pathtrie.py
File metadata and controls
59 lines (46 loc) · 1.5 KB
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
50
51
52
53
54
55
56
57
58
59
class TrieNode:
def __init__(self, value: str):
self.value = value
self.children = [None] * 26
self.isEndOfWord = False
def __str__(self):
return "value=" + self.value
class Trie:
def __init__(self):
self.root = TrieNode("")
def insert(self, word: str):
current = self.root
for ch in word:
index = self.__charToIndex(ch)
# if we don't have this child, we will create it
if not current.children[index]:
current.children[index] = TrieNode(ch)
# Then point current to that node
current = current.children[index]
# After visit all the characters
# set the last node to end of word
current.isEndOfWord = True
def __charToIndex(self, char: str):
# Private helper function
# converts key current character into index
# use only "a" through "z" and lower case
return ord(char) - ord("a")
def search(self, word: str):
# Search word in the trie
# Return True if word presents in trie
# else False
current = self.root
for ch in word:
index = self.__charToIndex(ch)
if not current.children[index]:
return False
current = current.children[index]
return current.isEndOfWord
# driver function
def main():
keys = ["cat", "can"]
t = Trie()
for key in keys:
t.insert(key)
if __name__ == "__main__":
main()