Created
June 21, 2019 20:37
-
-
Save eyaltrabelsi/7a774231e46be768ba99999bec8b1376 to your computer and use it in GitHub Desktop.
Python tricks calculating ngrams with slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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