Skip to content

Commit 75f9a70

Browse files
authored
Add files via upload
1 parent c4cd77c commit 75f9a70

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Trie_using_Array.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#Trie Data structure
2+
class TrieNode:
3+
def __init__(self):
4+
self.children = [None] * 26
5+
self.isEnd = False
6+
7+
class Trie:
8+
'''Creates a Trie Data Stucture.'''
9+
def __init__(self):
10+
self.root = TrieNode()
11+
12+
def _charToIndex(self, ch):
13+
'''Helper Function to find the index of a character in the range [0,25].'''
14+
return ord(ch) - ord('a')
15+
16+
def insert(self, key):
17+
'''Inserts a word/key into the Trie.'''
18+
t_root = self.root
19+
length = len(key)
20+
for i in range(length):
21+
idx = self._charToIndex(key[i])
22+
23+
if not t_root.children[idx]:
24+
t_root.children[idx] = TrieNode()
25+
t_root = t_root.children[idx]
26+
27+
t_root.isEnd = True
28+
29+
def search(self, key):
30+
'''Returns True is given word is present in the Trie, else returns False.'''
31+
t_root = self.root
32+
length = len(key)
33+
for i in range(length):
34+
idx = self._charToIndex(key[i])
35+
if not t_root.children[idx]:
36+
return False
37+
t_root = t_root.children[idx]
38+
39+
return t_root != None and t_root.isEnd
40+
41+
def startsWith(self, key):
42+
'''Returns True if given word is present as a prefix in the Trie, else returns False.'''
43+
t_root = self.root
44+
length = len(key)
45+
for i in range(length):
46+
idx = self._charToIndex(key[i])
47+
if not t_root.children[idx]:
48+
return False
49+
t_root = t_root.children[idx]
50+
51+
return True
52+
53+
54+
#Driver Code
55+
keys = ['the', 'their', 'there', 'they', 'these', 'thesis', 'apple', 'appy', 'cat', 'catfish', 'cattle', 'cats']
56+
57+
#Creating a Trie Object
58+
t = Trie()
59+
60+
#Inserting Keys into the Trie
61+
for key in keys:
62+
t.insert(key)
63+

0 commit comments

Comments
 (0)