-
Notifications
You must be signed in to change notification settings - Fork 1
/
py_trie.py
60 lines (43 loc) · 1.34 KB
/
py_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
48
49
50
51
52
53
54
55
56
57
58
59
60
import string
class TrieNode():
def __init__(self, letter, is_word=False):
self.letter = letter
self.is_word = is_word
self.children = [None for _ in string.ascii_lowercase]
class PyTrie():
"""
trie = PyTrie()
trie.add("bob")
trie.find("bob")
True
"""
def __init__(self):
self.head = TrieNode("\0", is_word=False)
@staticmethod
def char_to_idx(letter):
return ord(letter) - 97 # ascii for a is 97
def add(self, new_word):
""" Add a given word to trie, returns None"""
cur = self.head
for char in new_word:
child = cur.children[PyTrie.char_to_idx(char)]
if not child:
new_node = TrieNode(char)
cur.children[PyTrie.char_to_idx(char)] = new_node
cur = cur.children[PyTrie.char_to_idx(char)]
cur.is_word = True
return None
def find(self, word):
""" Returns boolean if word in trie or not """
cur = self.head
for char in word:
child = cur.children[PyTrie.char_to_idx(char)]
if not child:
return False
cur = child
return cur.is_word == True
def test_trie():
assert trie.find("bob") == True
assert trie.find("alice") == False
if __name__ == "__main__":
test_trie()