Page 1 of 1

N-gram is a list of lists, where an inner list is a group of n consecutive words, and the outer list contains those grou

Posted: Wed Apr 27, 2022 3:50 pm
by answerhappygod
N-gram is a list of lists, where an inner list is a group of n
consecutive words, and the outer list contains those groups for a
given sentence. For example, the sentence 'this is a long sentence'
with n=3 will make:
As above, the inner list is 3 consecutive words, and the outer
list is all those 3-gram words generated from the example
sentence.
For this task, write a function construct_ngrams(sentence,
n) which takes input parameters sentence (type
string) and n (type integer), and returns a
list that contains N-gram generated from the
given sentence. If no such N-gram could be generated (think
about the cases), then it simply returns an empty list.
Note: Although a more elegant solution could be generated using
the zip function, you cannot use that for this question
(as we are practising primitive Python coding skills).
For example, codes must past all these tests:
Test
Expected
ngrams = construct_ngrams('this is a long sentence', 3)
print(ngrams)
[['this', 'is', 'a'], ['is', 'a', 'long'], ['a', 'long',
'sentence']]
ngrams = construct_ngrams('this is a long sentence', 6)
print(ngrams)
[]
ngrams = construct_ngrams('this is another long sentence for
testing', 4)
print(ngrams)
[['this', 'is', 'another', 'long'], ['is', 'another', 'long',
'sentence'], ['another', 'long', 'sentence', 'for'], ['long',
'sentence', 'for', 'testing']]
ngrams = construct_ngrams('this is another long sentence for
testing', 6)
print(ngrams)
[['this', 'is', 'another', 'long', 'sentence', 'for'], ['is',
'another', 'long', 'sentence', 'for', 'testing']]