Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 885c4b3

Browse files
Merge pull request fnplus#441 from amitrajitbose/trie-python
Add Trie implementation in Python
2 parents 1f9ec4c + 3fbd222 commit 885c4b3

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎Data Structures/Trie/Trie.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /