class TrieNode(defaultdict):
def __init__(self):
self.default_factory = TrieNode
self.terminal = False
def add(root, word):
node = root
for c in word:
node = node[c]
node.terminal = True
def contains(root, word):
node = root
for i, c in enumerate(word):
if c not in node: return False
node = node[c]
return node.terminal
def startswith(root, word):
node = root
for c in word:
if c not in node: return False
node = node[c]
return True
root = TrieNode()
words = ["hello", "hell", "hehe", "what"]
for word in words: add(root, word)
queries = ["hello", "hel", "he", "w", "are"]
for query in queries: print(f"{query} in trie: {contains(root, query)}")
for query in queries: print(f"{query} is a prefix in trie: {startswith(root, query)}")