University of Arizona, Department of Computer Science

CSc 120: N-grams (List comprehension)

Expected Behavior

Write a Python function get_ngrams(seq, n) that takes as arguments a string seq and an integer n, and returns a set consisting of the n-grams of seq.

Your solution should use only a list comprehension and a call to Python's set() function. It should not use any other control statements—i.e., no if, for, while, or try statements, except as needed within the list comprehension.

Examples

  1. Call: get_ngrams("abcdabcdabcdabc", 3)
    Return value: {'bcd', 'abc', 'cda', 'dab'}

  2. Call: get_ngrams("aaaaaaaaaaaaaaa", 3)
    Return value: {'aaa'}

  3. Call: get_ngrams("abcdabcdabcdabc", 5)
    Return value: {'bcdab', 'cdabc', 'abcda', 'dabcd'}

  4. Call: get_ngrams('a',3)
    Return value: set()
    This return value denotes the empty set.