1
+ '''
2
+ Node class to create a node
3
+ for trie
4
+ '''
5
+
1
6
class Node :
2
7
def __init__ (self , v , p = None , w = False ):
3
8
self .word = w #If the node represents the end of a word or not
@@ -10,9 +15,9 @@ class Trie:
10
15
def __init__ (self ):
11
16
self .root = Node ('' ) #The root of the trie is always empty
12
17
13
- def Insert (self , word ):
18
+ def insert (self , word ):
14
19
"""
15
- Insert word in the trie. Starting from the root, move down the trie
20
+ Inserts a word in the trie. Starting from the root, move down the trie
16
21
following the path of characters in the word. If the nodes for the word
17
22
characters end, add them. When the last char is added, mark it as a
18
23
word-ending node.
@@ -34,29 +39,29 @@ def Insert(self, word):
34
39
35
40
curr = curr .children [c ]
36
41
37
- def Search (self , word ):
42
+ def search (self , word ):
38
43
"""
39
44
Searches for given word in trie. We want to find the last node for the
40
45
word. If we can't, then it means the word is not in the trie.
41
46
"""
42
- if self .FindFinalNode (word ):
47
+ if self .find_final_node (word ):
43
48
return True
44
49
else :
45
50
return False
46
51
47
- def FindWords (self , prefix ):
52
+ def find_words (self , prefix ):
48
53
"""
49
54
Find all words with the given prefix
50
55
"""
51
- v = self .FindFinalNode (prefix )
52
- wList = self .BuildWordList (v , prefix )
56
+ v = self .find_final_node (prefix )
57
+ wList = self .build_word_list (v , prefix )
53
58
if (v and v .word ):
54
59
#v exists and the prefix is itself a word; add it to the list.
55
60
wList .append (prefix )
56
61
57
62
return wList
58
63
59
- def FindFinalNode (self , word ):
64
+ def find_final_node (self , word ):
60
65
"""
61
66
Returns the last node in given word. The process goes like this:
62
67
Start from the root. For every char in word, go down one level.
@@ -81,7 +86,7 @@ def FindFinalNode(self, word):
81
86
82
87
return None
83
88
84
- def BuildWordList (self , v , cWord ):
89
+ def build_word_list (self , v , cWord ):
85
90
"""
86
91
Recursively builds the list of words.
87
92
* v: Node to check
@@ -99,6 +104,6 @@ def BuildWordList(self, v, cWord):
99
104
wList .append (tempWord )
100
105
101
106
#The list of words under tWord
102
- wList .extend (self .BuildWordList (k , tempWord ))
107
+ wList .extend (self .build_word_list (k , tempWord ))
103
108
104
109
return wList
0 commit comments