1
- '''
1
+ """
2
2
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
3
3
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
4
4
making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup
5
5
time making it an optimal approach when space is not an issue.
6
- '''
6
+
7
+ This implementation assumes the character $ is not in any of the words. This character is used in the implementation
8
+ to mark the end of a word.
9
+ """
7
10
8
11
9
12
class TrieNode :
10
13
def __init__ (self ):
11
- self .nodes = dict () # Mapping from char to TrieNode
14
+ self .nodes = dict () # Mapping from char to TrieNode
12
15
13
16
def insert_many (self , words : [str ]):
17
+ """
18
+ Inserts a list of words into the Trie
19
+ :param words: list of string words
20
+ :return: None
21
+ """
14
22
for word in words :
15
23
self .insert (word )
16
24
17
25
def insert (self , word : str ):
18
- pass
26
+ """
27
+ Inserts a word into the Trie
28
+ :param word: word to be inserted
29
+ :return: None
30
+ """
31
+ word += '$'
32
+ curr = self
33
+ for char in word :
34
+ if char not in curr .nodes :
35
+ curr .nodes [char ] = TrieNode ()
36
+ curr = curr .nodes [char ]
19
37
20
38
def find (self , word : str ) -> bool :
21
- pass
39
+ """
40
+ Tries to find word in a Trie
41
+ :param word: word to look for
42
+ :return: Returns True if word is found, False otherwise
43
+ """
44
+ word += '$'
45
+ curr = self
46
+ for char in word :
47
+ if char not in curr .nodes :
48
+ return False
49
+ curr = curr .nodes [char ]
50
+ return True
51
+
52
+
53
+ def print_words (node : TrieNode , word : str ):
54
+ """
55
+ Prints all the words in a Trie
56
+ :param node: root node of Trie
57
+ :param word: Word variable should be empty at start
58
+ :return: None
59
+ """
60
+ if '$' in node .nodes :
61
+ print (word , end = ' ' )
62
+
63
+ for key , value in node .nodes .items ():
64
+ print_words (value , word + key )
65
+
66
+
67
+ def test ():
68
+ words = ['banana' , 'bananas' , 'bandana' , 'band' , 'apple' , 'all' , 'beast' ]
69
+ root = TrieNode ()
70
+ root .insert_many (words )
71
+ # print_words(root, '')
72
+ assert root .find ('banana' )
73
+ assert not root .find ('bandanas' )
74
+ assert not root .find ('apps' )
75
+ assert root .find ('apple' )
76
+
77
+ # test()
0 commit comments