2/35
Part 1 of 7 · Dict of dictsLearn and do
A trie is a dict of dicts
A search box that suggests as you type asks one question on every keystroke: which names start with what's been typed so far? A set can't answer that well. It finds tent with one hash, but for te it has to check every name.
# a key that's never a letter: a whole word ends here
END = "$"
def insert(trie, word):
node = trie
for ch in word:
# the child for ch, made empty if it isn't there yet
node = node.setdefault(ch, {})
node[END] = True
CATALOG = ["tent", "tents", "tarp", "tea", "lamp", "lantern"]
trie = {}
for word in CATALOG:
insert(trie, word)
print(trie["t"]["e"])
{'n': {'t': {'$': True, 's': {'$': True}}}, 'a': {'$': True}}
That's the node for te. A node is a dict from each next letter to the child node, and '$' says a whole word ends at that node. setdefault(ch, {}) follows a letter that's there and makes an empty child for one that isn't.
Here are the six items from an outdoor shop, going in one at a time.
The six words have 27 letters in all. How many nodes do they need below the top?
Pick an answer above to see the rest