I want to be able to return the count of partial words present using Tries. What would be the best way to implement this in Python?
Example:
Input
4
add hack
add hackerrank
find hac
find hak
Expected output
2
0
Please follow the link below to the problem! https://www.hackerrank.com/challenges/ctci-contacts/problem
Edit:
from collections import defaultdict
n = int(input().strip())
class Trie:
def __init__(self):
self.root= dict()
def insert(self,word):
current = self.root
for letter in word:
exist = False
for (t1,t2) in current:
if t1==letter:
current[(t1,t2+1)] = current.pop((t1,t2))
current = current[(t1,t2+1)]
exist = True
break
if exist==False:
current[(letter,1)] = {}
current = current[(letter,1)]
def search(self,word):
current = self.root
count = 0
for letter in word:
found = False
for (t1,t2) in current:
if t1==letter:
current = current[(t1,t2)]
found = True
count = t2
break
if found == False:
return 0
return count
def printDict(self):
print(self.root)
for a0 in range(n):
op, contact = input().strip().split(' ')
T = Trie()
if op == 'add':
T.insert(contact)
T.printDict()
else:
print(T.search(contact))
I am using Tuples as keys to the dictionaries. I know its messy but I want to store the count of the contacts as well.