Created
December 1, 2021 14:42
-
-
Save dutc/4e2cdf42469548094ed22090b6634571 to your computer and use it in GitHub Desktop.
`nwise` and friends!
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
#!/usr/bin/env python3 | |
from itertools import tee, islice, zip_longest, chain, repeat | |
nwise = lambda g, *, n=2: zip(*(islice(g, i, None) for i, g in enumerate(tee(g, n)))) | |
nwise_longest = lambda g, *, n=2, fv=object(): zip_longest(*(islice(g, i, None) for i, g in enumerate(tee(g, n))), fillvalue=fv) | |
first = lambda g, *, n=1: zip(chain(repeat(True, n), repeat(False)), g) | |
last = lambda g, *, m=1, s=object(): ((xs[-1] is s, x) for x, *xs in nwise_longest(g, n=m+1, fv=s)) | |
if __name__ == '__main__': | |
print( | |
f"{[*nwise('abcd')] = }", | |
f"{[*nwise_longest('abcd')] = }", | |
f"{[*first('abcd')] = }", | |
f"{[*last('abcd')] = }", | |
sep='\n', | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment