10/35
Part 3 of 7 · AutocompleteLearn and do

Autocomplete: the best k under a prefix

Autocomplete asks for the best few words under what's been typed.

Typing te should show a few suggestions, the best first. That's two steps: find the node for the prefix, then collect every word below it. The collecting is the depth-first-search lesson's walk with your own stack, carrying the string spelled so far. Let the end marker hold each word's score, so the walk can rank:

import heapq


def insert_scored(trie, word, score):
    node = trie
    for ch in word:
        node = node.setdefault(ch, {})
    # the marker now carries the word's score
    node[END] = score


# highest score first, ties in alphabetical order
def best_k(trie, prefix, k):
    pairs = words_under(trie, prefix)
    return [word for _, word in heapq.nsmallest(k, pairs, key=lambda p: (-p[0], p[1]))]


SCORES = {"tent": 120, "tents": 45, "tarp": 120, "tea": 300, "lamp": 95, "lantern": 60}
scored = {}
for word, score in SCORES.items():
    insert_scored(scored, word, score)
print(words_under(scored, "te"))
print(best_k(scored, "t", 3))
print(best_k(scored, "tent", 3))
print(best_k(scored, "x", 3))
Predict

best_k(scored, "t", 3), with tea 300, tarp 120, tent 120 and tents 45. What comes back?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

words_under pushes ten, then tea, and pops from the end of its stack. Which word does it find first?

Pick an answer above to see the rest