Skip to content

Instantly share code, notes, and snippets.

@ratpik
Last active October 13, 2016 13:54
Show Gist options
  • Save ratpik/33cd4d04a8f6b21ad9512588c2e3d226 to your computer and use it in GitHub Desktop.
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
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)
4
add hack
add hackerrank
find hac
find hak
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment