forked from krishna14kant/Data-Structures-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie_Data_Structure.py
More file actions
64 lines (56 loc) · 1.55 KB
/
Trie_Data_Structure.py
File metadata and controls
64 lines (56 loc) · 1.55 KB
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
53
54
55
56
57
58
59
60
61
62
63
import time
class TrieNode:
children = {}
endofword = False
def __init__(self):
self.children = {}
self.endofword = False
self.count = 0
root = TrieNode()
def insert(word):
current = root
for i in range(len(word)):
if word[i] not in current.children:
node = TrieNode()
current.children[word[i]] = node
else:
node = current.children[word[i]]
current = node
current.endofword = True
current.count += 1
lis = []
def printTrie(current):
for char, node in current.children.items():
print(char,end='')
lis.append(node)
print("")
if lis:
nextnode = lis.pop()
printTrie(nextnode)
def search(word,root):
current = root
for i in range(len(word)):
if word[i] not in current.children:
return False
else:
node = current.children[word[i]]
current = node
return {"The word exists" : current.endofword,"No of times word occurs" : current.count}
start = time.process_time()
print("Reading the File")
store = open("store_for_trie.txt","r",encoding="utf8")
text = store.read()
words = text.split()
print("Calculating the number of words")
print("No of words: " + str(len(words)))
print(">>TIME: "+str(time.process_time() - start))
starts = time.process_time()
print("Creating Trie Data Structure")
for word in words:
insert(word)
print("Trie Successfully Created")
print(">>TIME: "+str(time.process_time() - starts))
startss = time.process_time()
tosearch = input("enter the word to search: ")
print(search(tosearch,root))
print(">>TIME: "+str(time.process_time() - startss))