Skip to content

Commit acf2032

Browse files
Merge pull request #188 from jerryderry/trie-python
trie in python
2 parents 41046e4 + 7b203f1 commit acf2032

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

python/35_trie/trie.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Author: Wenru Dong
3+
"""
4+
5+
class TrieNode:
6+
def __init__(self, data: str):
7+
self._data = data
8+
self._children = [None] * 26
9+
self._is_ending_char = False
10+
11+
12+
class Trie:
13+
def __init__(self):
14+
self._root = TrieNode("/")
15+
16+
def insert(self, text: str) -> None:
17+
node = self._root
18+
for index, char in map(lambda x: (ord(x) - ord("a"), x), text):
19+
if not node._children[index]:
20+
node._children[index] = TrieNode(char)
21+
node = node._children[index]
22+
node._is_ending_char = True
23+
24+
def find(self, pattern: str) -> bool:
25+
node = self._root
26+
for index in map(lambda x: ord(x) - ord("a"), pattern):
27+
if not node._children[index]: return False
28+
node = node._children[index]
29+
return node._is_ending_char
30+
31+
32+
if __name__ == "__main__":
33+
34+
strs = ["how", "hi", "her", "hello", "so", "see"]
35+
trie = Trie()
36+
for s in strs:
37+
trie.insert(s)
38+
39+
for s in strs:
40+
print(trie.find(s))
41+
42+
print(trie.find("swift"))

0 commit comments

Comments
 (0)