Skip to content

Commit b3ef921

Browse files
Merge pull request #656 from dashan124/patch-1
Create trie.py
2 parents ebc05b8 + 6ae64df commit b3ef921

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Data Structures/Trie/trie.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Trienode:
2+
def __init__(self):
3+
self.ch=[None]*26
4+
self.endofword=None
5+
class Tries:
6+
def __init__(self):
7+
self.head=None
8+
def findkey(self,x):
9+
if ord(x)>=97 and ord(x)<=122:
10+
return ord(x)-97
11+
if ord(x)>=65 and ord(x)<=90:
12+
return ord(x)-65
13+
14+
def add(self,s):
15+
if self.head==None:
16+
self.head=Trienode()
17+
tmp=self.head.ch
18+
for i in range(len(s)):
19+
key=self.findkey(s[i])
20+
if tmp[key]==None:
21+
tmp[key]=Trienode()
22+
if i!=len(s)-1:
23+
tmp=tmp[key].ch
24+
else:
25+
tmp[key].endofword='#'
26+
def search(self,s):
27+
if self.head==None:
28+
print("Not Found")
29+
else:
30+
tmp=self.head.ch
31+
for i in range(len(s)):
32+
key=self.findkey(s[i])
33+
if tmp[key]==None:
34+
print("Not found")
35+
return
36+
else:
37+
tempo=tmp
38+
tmp=tmp[key].ch
39+
if tempo[key].endofword=='#':
40+
print("FOUND")
41+
else:
42+
print("Not Found")
43+
t=Tries()
44+
t.add("apple")
45+
t.add("ball")
46+
t.search("apple")

0 commit comments

Comments
 (0)