Created
February 29, 2012 14:29
-
-
Save mattdeboard/1941210 to your computer and use it in GitHub Desktop.
Recursive generation of slice start/end points for a collection for convenient iteration
This file contains hidden or 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
| def take(n, seq): | |
| "Return first n items of the seq as a list" | |
| return list(islice(seq, n)) | |
| def drop(n, seq): | |
| "Return seq with the first n items removed." | |
| return list(islice(seq, n, None, 1)) | |
| def split_by(n, seq): | |
| return [take(n, seq), drop(n, seq)] | |
| def slices(seq, start=0, end=None, step=2, accum=None): | |
| if accum == None: | |
| accum = [] | |
| if step == 1: | |
| return seq | |
| elif step == 0: | |
| return [] | |
| if len(seq) < step and seq: | |
| accum.append((seq[-(len(seq))], seq[-1])) | |
| return accum | |
| elif not seq: | |
| return accum | |
| else: | |
| seg = split_by(step, seq) | |
| accum.append((seg[0][0], seg[0][-1])) | |
| return slices(seg[1], start=start, end=end, step=step, accum=accum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment