1+ '''
2+ Node class to create a node
3+ for trie
4+ '''
5+
16class Node :
27 def __init__ (self , v , p = None , w = False ):
38 self .word = w #If the node represents the end of a word or not
@@ -10,9 +15,9 @@ class Trie:
1015 def __init__ (self ):
1116 self .root = Node ('' ) #The root of the trie is always empty
1217
13- def Insert (self , word ):
18+ def insert (self , word ):
1419 """
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
1621 following the path of characters in the word. If the nodes for the word
1722 characters end, add them. When the last char is added, mark it as a
1823 word-ending node.
@@ -34,29 +39,29 @@ def Insert(self, word):
3439
3540 curr = curr .children [c ]
3641
37- def Search (self , word ):
42+ def search (self , word ):
3843 """
3944 Searches for given word in trie. We want to find the last node for the
4045 word. If we can't, then it means the word is not in the trie.
4146 """
42- if self .FindFinalNode (word ):
47+ if self .find_final_node (word ):
4348 return True
4449 else :
4550 return False
4651
47- def FindWords (self , prefix ):
52+ def find_words (self , prefix ):
4853 """
4954 Find all words with the given prefix
5055 """
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 )
5358 if (v and v .word ):
5459 #v exists and the prefix is itself a word; add it to the list.
5560 wList .append (prefix )
5661
5762 return wList
5863
59- def FindFinalNode (self , word ):
64+ def find_final_node (self , word ):
6065 """
6166 Returns the last node in given word. The process goes like this:
6267 Start from the root. For every char in word, go down one level.
@@ -81,7 +86,7 @@ def FindFinalNode(self, word):
8186
8287 return None
8388
84- def BuildWordList (self , v , cWord ):
89+ def build_word_list (self , v , cWord ):
8590 """
8691 Recursively builds the list of words.
8792 * v: Node to check
@@ -99,6 +104,6 @@ def BuildWordList(self, v, cWord):
99104 wList .append (tempWord )
100105
101106 #The list of words under tWord
102- wList .extend (self .BuildWordList (k , tempWord ))
107+ wList .extend (self .build_word_list (k , tempWord ))
103108
104109 return wList
0 commit comments