1
+
2
+ class TrieNode (object ):
3
+ def __init__ (self ):
4
+ self .children = [] #will be of size = 26
5
+ self .isLeaf = False
6
+
7
+ def getNode (self ):
8
+ p = TrieNode () #new trie node
9
+ p .children = []
10
+ for i in range (26 ):
11
+ p .children .append (None )
12
+ p .isLeaf = False
13
+ return p
14
+
15
+ def insert (self , root , key ):
16
+ key = str (key )
17
+ pCrawl = root
18
+ for i in key :
19
+ index = ord (i )- 97
20
+ if (pCrawl .children [index ] == None ):
21
+ # node has to be initialised
22
+ pCrawl .children [index ] = self .getNode ()
23
+ pCrawl = pCrawl .children [index ]
24
+ pCrawl .isLeaf = True #marking end of word
25
+
26
+ def search (self , root , key ):
27
+ #print("Searching %s" %key) #DEBUG
28
+ pCrawl = root
29
+ for i in key :
30
+ index = ord (i )- 97
31
+ if (pCrawl .children [index ] == None ):
32
+ return False
33
+ pCrawl = pCrawl .children [index ]
34
+ if (pCrawl and pCrawl .isLeaf ):
35
+ return True
36
+
37
+ def main ():
38
+ root = TrieNode ().getNode ()
39
+ root .insert (root , "elephant" )
40
+ root .insert (root , "tiger" )
41
+ root .insert (root , "timothy" )
42
+ search = input ("Enter the word to search for: " )
43
+ if root .search (root , search ):
44
+ print ("The word:" , search , "exists" )
45
+ else :
46
+ print ("The given word doesnt exist" )
47
+ if __name__ == '__main__' :
48
+ main ()
0 commit comments