Skip to content
DeepForgeby svx
All problems
EasyNLPnlp-004

N-grams

Problem

Generate all n-grams of length n from a list of tokens.

Return a list of lists, where each inner list is a slice of n consecutive tokens.

If n <= 0 or len(tokens) < n, return an empty list.

Test cases

case 1
in: [["a","b","c","d"],2]
expected: [["a","b"],["b","c"],["c","d"]]
case 2
in: [["a","b","c"],3]
expected: [["a","b","c"]]
case 3
in: [["a","b"],3]
expected: []
case 4
in: [["a","b","c"],1]
expected: [["a"],["b"],["c"]]
Starter codePython
def ngrams(tokens, n):
    # Your code here
    pass

4 test cases · run your code against them in the editor