Count word n-grams and return the k most frequent with stable ties

Why it matters N-gram counts drive keyword extraction, BLEU-style metrics and repetition penalties in LLM decoding.

N-gram counts are the base of classic language models, keyword extraction and repetition checks in generated text. The sliding loop is easy to get off by one, which silently drops the last n-gram.

Write top_ngrams(tokens, n, k). tokens is a list of str. Count every contiguous n-gram as a tuple of n tokens. Return a list of at most k pairs (ngram_tuple, count) sorted by count descending, then by the n-gram tuple ascending. If len(tokens) < n, return [].

Signaturedef top_ngrams(tokens, n, k)

Example

top_ngrams(['a', 'b', 'a', 'b', 'c'], 2, 2) is [(('a', 'b'), 2), (('b', 'a'), 1)].

Understand the idea

An n-gram is a run of n consecutive tokens. Bigrams are pairs, trigrams are triples. A text of L tokens has L - n + 1 n-grams, one starting at each position where a full window still fits.

Worked example: tokens a b a b c with n = 2. Windows start at 0, 1, 2, 3: (a, b), (b, a), (a, b), (b, c). That is 5 - 2 + 1 = 4 bigrams. Counts: (a, b) = 2, (b, a) = 1, (b, c) = 1. The top 2 by count, ties broken alphabetically, are (a, b) with 2 and (b, a) with 1.

Rule: grams = [tokens[i:i + n] for i in 0 .. L - n]. Sort by (-count, gram) for stable ties.

N-gram counts power classic language models, BLEU and ROUGE, keyword extraction and no-repeat-n-gram rules in LLM decoding.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletop_ngrams(['a', 'b', 'a', 'b', 'c'], 2, 2)
  • Sample 2: last n-gram matterstop_ngrams('to be or not to be'.split(), 2, 3)
  • Test 3: trigramstop_ngrams('the cat sat the cat sat the cat ran'.split(), 3, 2)
  • Test 4: too shorttop_ngrams(['x'], 2, 5)