xxxxxxxxxx
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in word:
if char not in current.children:
current.children[char] = TrieNode()
current = current.children[char]
current.is_word = True
def search(self, word):
current = self.root
for char in word:
if char not in current.children:
return False
current = current.children[char]
return current.is_word
def starts_with(self, prefix):
current = self.root
for char in prefix:
if char not in current.children:
return False
current = current.children[char]
return True
# Example usage:
trie = Trie()
trie.insert("apple")
trie.insert("banana")
trie.insert("cherry")
print(trie.search("apple")) # True
print(trie.search("banana")) # True
print(trie.search("cherry")) # True
print(trie.search("dog")) # False
print(trie.starts_with("app")) # True
print(trie.starts_with("ban")) # True
print(trie.starts_with("che")) # True
print(trie.starts_with("dog")) # False
xxxxxxxxxx
# A very simple trie to put together quickly for coding problems
WORD_KEY = '$'
def build_trie(words, trie = dict()):
for word in words: # Add each word - letter by letter
node = trie
for letter in word:
node = node.setdefault(letter, {}) # node = node[letter].child
node[WORD_KEY] = word # Mark "leaf" with word
return trie
def exists(trie, word, index = 0):
if index >= len(word): return trie.get(WORD_KEY, None) == word
return trie.get(WORD_KEY, None) == word or (word[index] in trie and exists(trie[word[index]], word, index + 1))
# API
trie = build_trie(["hello", "hello again", "bye"])
assert exists(trie, "hello")
assert exists(trie, "hello again")
assert exists(trie, "bye")
assert not exists(trie, "")
assert not exists(trie, "hel")
trie = build_trie(["bye again", "will miss you"], trie)
assert exists(trie, "hello")
assert exists(trie, "hello again")
assert exists(trie, "bye")
assert exists(trie, "bye again")
assert not exists(trie, "")
assert not exists(trie, "hel")
assert not exists(trie, "hello ")
assert not exists(trie, "hello ag")
assert not exists(trie, "byebye")