v9.1.1
Menu

Next Word Predictor

easyFREELanguage ModelingNLP 3: Advanced

Given a corpus and a context word, predict the most likely next word using bigram counts.

If there are ties, return the word that comes first alphabetically.

Input format:

  • Line 1: The training corpus (lowercase)
  • Line 2: The context word

Output: The predicted next word and its probability (rounded to 4 decimal places but not padded with zeros: 2/32/3 prints as 0.6667, 1/21/2 as 0.5, and 11 as 1.0), separated by a space.

Example

Input
i like cats i like dogs i hate rain
i
Output
like 0.6667
Reasoning
  • Inputs: the corpus is the string i like cats i like dogs i hate rain, nine words in order, and the context is i. A bigram is a pair of adjacent words (wk,wk+1)(w_k, w_{k+1}), so this corpus contains 8 of them.
  • Bigrams that start with the context: i appears three times, and the word right after it is "like", "like", "hate". So C(i,like)=2C(i, \text{like}) = 2, C(i,hate)=1C(i, \text{hate}) = 1, and the total is C(i)=3C(i) = 3.
  • Prediction: the most frequent follower is "like" (2 beats 1), so no tie-break is needed here. If "hate" also had count 2, alphabetical order would pick "hate".
  • Probability: P(like∣i)=C(i,like)C(i)=23≈0.6667P(\text{like} \mid i) = \frac{C(i, \text{like})}{C(i)} = \frac{2}{3} \approx 0.6667 after rounding to 4 decimal places, giving like 0.6667.
  • Notice: the denominator counts only occurrences of the context that are followed by some word. A context that sits only at the very end of the corpus has no followers at all.

Constraints

  • All text is lowercase
  • Return most frequent next word after the context word
  • Ties broken alphabetically
  • Output: "word probability"
  • If context word never appears, output "N/A 0.0"

Learn this in

More from NLP 3: Advanced

solution.py

Test results

Sign in to run your code against the test cases.