Next Word Predictor
GoogleOnsiteMedium
Each test creates one Predictor instance and calls its methods in order. The output lists every method call's return value; calls that return None record null.
Part 1: Most frequent next word
You are building a word predictor that learns from sequences of words.
train(words) counts, for every pair of adjacent words in words, how many times the second word immediately follows the first. Pairs never span two train calls: the last word of one call is not followed by the first word of the next.
predict(word) returns the word that most often followed word, or None if word has never been followed by anything. When several words tie on count, return the one that first appeared after word earliest across all training.
predict is called far more often than train, so a predict call should take constant time on average.
- Example 1
- init
[]- operations
[["train",[["go","left","go","right","go","left"]]],["predict",["go"]],["predict",["left"]],["predict",["right"]],["predict",["stop"]],["train",[["go","right"]]],["predict",["go"]]]- Output
[null,"left","go","go",null,null,"left"]
Why: After the first sequence,
gois followed bylefttwice andrightonce, sopredict(go)isleft. Bothleftandrightare followed bygoonce. The lasttraincall raisesrightto 2, tying withleft;leftfollowedgofirst, sopredict(go)staysleft. A word never seen as a predecessor, likestop, givesNone.
Constraints
1 <= len(operations) <= 10^51 <= len(words) <= 10^4for eachtraincall1 <= len(word) <= 10'a' <= word[i] <= 'z'