3/35
Part 1 of 7 · Dict of dictsLearn and do
The end marker is a key inside the node, so one node can be a word and a prefix
With words in the trie, every question is a lookup.
# the node that s leads to, or None
def find_node(trie, s):
node = trie
for ch in s:
node = node.get(ch)
if node is None:
return None
return node
def has_word(trie, word):
node = find_node(trie, word)
return node is not None and END in node
def has_prefix(trie, prefix):
return find_node(trie, prefix) is not None
print(find_node(trie, "ten"))
print(has_prefix(trie, "ten"), has_word(trie, "ten"))
print(has_word(trie, "tent"), has_prefix(trie, "tex"))
{'t': {'$': True, 's': {'$': True}}}
True False
True False
Every lookup is the same walk down from the top. What decides the answer is where the walk ends:
tent
t
→e
→n
→t$
an end marker there: a word
ten
t
→e
→nno $
the node exists, with no end marker: a prefix
tex
t
→e
→xno child
the walk falls off: neither
The node for ten exists, because tent passes through it, but nobody inserted ten, so it has no end marker.
tent is a word even though tents goes on below it. A node can be both, which is why the marker is a key inside the node and not a kind of node. Use a key that can't be a letter of any word: "$" works for lowercase words.
In the editor, write longest_word_prefix(trie, text). It finds the longest word at the start of three texts.