-
Notifications
You must be signed in to change notification settings - Fork 6
/
Trie_using_Dictionary.py
52 lines (40 loc) · 1.24 KB
/
Trie_using_Dictionary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#Trie Data structure
# '$' denotes the end of the word
class Trie:
'''Creates a Trie Data Stucture.'''
def __init__(self):
self.Trie = {}
def insert(self, key):
'''Inserts a word/key into the Trie.'''
t = self.Trie
for i in key:
if i not in t:
t[i] = {}
t = t[i]
#Marking the end of the word
t['$'] = '$'
def search(self, key):
'''Returns True is given word is present in the Trie, else returns False.'''
t = self.Trie
for i in key:
if i not in t:
return False
t = t[i]
if '$' in t:
return True
return False
def startsWith(self, key):
'''Returns True if given word is present as a prefix in the Trie, else returns False.'''
t = self.Trie
for i in key:
if i not in t:
return False
t = t[i]
return True
#Driver Code
keys = ['the', 'their', 'there', 'they', 'these', 'thesis', 'apple', 'appy', 'cat', 'catfish', 'cattle', 'cats']
#Creating a Trie Object
t = Trie()
#Inserting Keys into the Trie
for key in keys:
t.insert(key)