Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add python implementaion of trie #268

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions classicalAlgos/tries/tries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
class Node:
def _init_(self):
self.children = [None] * 26
self.isEnd = False


class Trie:
def _init_(self):
self.root = Node()

def createNode(self):
return Node()

def _convertCharToIndex(self, ch):
return ord(ch) - ord('a')

def insert(self, word):
# If key is not present, inserts it into trie, else just mark the word to be completed, by traversing the trie sequentially.
currentNode = self.root
for i in range(len(word)):
index = self._convertCharToIndex(word[i])

# if current character is not present
if not currentNode.children[index]:
currentNode.children[index] = self.createNode()
currentNode = currentNode.children[index]

# mark last node as completing a word
currentNode.isEnd = True

def search(self, word):
current_node = self.root
for i in range(len(word)):
index = self._convertCharToIndex(word[i])

# return false immediately if the current character is not present in the trie.
if not current_node.children[index]:
return False
current_node = current_node.children[index]

# even if the control reaches the end, then we have to check if a word ends here.
return current_node.isEnd

# driver function here


def main():
# take input of the number of words and the number of queries
n = int(input("Enter the number of words: "))
q = int(input("Enter the number of queries: "))

t = Trie()
print("Enter the words: ")
while (n > 0):
word = input().strip()
t.insert(word)
n -= 1

print("Enter the queries: ")
while (q > 0):
word = input().strip()
if t.search(word):
print("YES")
else:
print("NO")
q -= 1


# the main function to run the script
if __name__ == '__main__':
# print("1")
main()