Skip to content

Instantly share code, notes, and snippets.

@eyaltrabelsi
Created June 21, 2019 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyaltrabelsi/7a774231e46be768ba99999bec8b1376 to your computer and use it in GitHub Desktop.
Save eyaltrabelsi/7a774231e46be768ba99999bec8b1376 to your computer and use it in GitHub Desktop.
Python tricks calculating ngrams with slice
>>> from itertools import islice
>>> def n_grams(a, n):
... z = (islice(a, i, None) for i in range(n))
... return zip(*z)
...
>>> a = [1, 2, 3, 4, 5, 6]
>>> n_grams(a, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> n_grams(a, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> n_grams(a, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment