Last active
October 13, 2016 13:54
-
-
Save ratpik/33cd4d04a8f6b21ad9512588c2e3d226 to your computer and use it in GitHub Desktop.
Trie Implementation - A way to search for strings and prefixes given a list of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, key=None, word_count=0): | |
self.key = key | |
self.word_count = word_count #Since word and prefix counts are same | |
self.edges = [] #List of Nodes | |
class Trie: | |
def __init__(self, root=None): | |
self.root = root | |
def add(self, word, node): | |
if len(word) == 0: | |
return | |
edge = filter(lambda w: w.key == word[0], node.edges) | |
if len(edge) > 0: | |
edge[0].word_count +=1 | |
self.add(word[1:], edge[0]) #Add the suffix excluding the first | |
else: | |
#Word not found | |
next = Node(key=word[0], word_count=1) | |
node.edges.append(next) | |
self.add(word[1:], node.edges[-1]) | |
def find(self, word, node): | |
if len(word) == 0: | |
return 0 | |
edge = filter(lambda w: w.key == word[0], node.edges) | |
if len(edge) > 0: | |
if len(word) == 1: | |
return edge[0].word_count | |
else: | |
return self.find(word[1:], edge[0]) | |
else: | |
return 0 | |
trie = Trie(root=Node()) | |
def add(word): | |
trie.add(word, trie.root) | |
def find(word): | |
print trie.find(word, trie.root) | |
n = int(raw_input().strip()) | |
for a0 in xrange(n): | |
op, contact = raw_input().strip().split(' ') | |
if op == "add": | |
add(contact) | |
else: | |
find(contact) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 | |
add hack | |
add hackerrank | |
find hac | |
find hak |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 | |
2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment