Skip to content

Instantly share code, notes, and snippets.

@dskecse
Created May 28, 2026 10:44
Show Gist options
  • Select an option

  • Save dskecse/8744b373ad85d2871c4c8f7380936b96 to your computer and use it in GitHub Desktop.

Select an option

Save dskecse/8744b373ad85d2871c4c8f7380936b96 to your computer and use it in GitHub Desktop.
import sys
def extract_ngrams(text: str, n: int = 2) -> list[str]:
if n < 1 or n > len(text):
print(f"Error: n should be within 1 and {len(text)}, instead it is: {n}")
sys.exit(1)
if n == 1:
return list(text)
return [text[i:i+n] for i in range(0, len(text) - n + 1)]
print(extract_ngrams("hello", n=2)) # => ["he", "el", "ll", "lo"]
print(extract_ngrams("hello", n=3)) # => ["hel", "ell", "llo"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment