Interview Query

N-Gram Count

Start Timer

0:00:00

Upvote
3
Downvote
Save question
Mark as completed
View comments (4)
Next question

Given a string, write a function ngram_count that returns a dictionary where the keys are the n-grams of the string and the values are the counts of each n-gram in the string. An n-gram is a contiguous sequence of n items from a given sample of text or speech.

Your function should take in two parameters: the string word and the integer n which represents the length of the n-grams.

Note: assume that n will always be a positive integer less than or equal to the length of the string, and word will always be a string with no spaces or punctuation.

Example:

Input:

word = 'banana'
n = 2

Output:

ngram_count(word, n) -> {'ba':1, 'an':2, 'na':2}

Example 2:

Input:

word = 'banana'
n = 3

Output:

ngram_count(word, n) -> {'ban':1, 'ana':2, 'nan':1}
.
.
.
.
.


Comments

Loading comments