Last active
May 27, 2020 00:13
-
-
Save MaurizioB/36b4b3238589483f67f9f0d4b4fb67ce to your computer and use it in GitHub Desktop.
Equally slice splitt a list based on step
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
def getSlices(l, step): | |
# stepCount, rest = divmod(len(l) - 1, step) | |
rest = (len(l) - 1) % step | |
if not rest: | |
return l[::step] | |
stepCount = len(l) // (rest + 1) | |
indexes = [0] | |
maxIndex = len(l) | |
i = 0 | |
# maybe done = step for short/odd lists? | |
done = 0 | |
while True: | |
i += step | |
done += step | |
if done >= stepCount: | |
done = 0 | |
i += 1 | |
if i >= maxIndex: | |
break | |
indexes.append(int(round(i))) | |
if i <= maxIndex: | |
indexes.append(-1) | |
print(i, maxIndex, stepCount, rest) | |
return [l[i] for i in indexes] | |
tests = [(0, 11, 1, 2), (0, 10, 1, 2), (0, 21, 1, 3), (1, 22, 1, 3), (0, 25, 1, 5), (0, 101, 1, 3)] | |
for minimum, ext, rangeStep, step in tests: | |
l = list(range(minimum, ext, rangeStep)) | |
print('Source list ({}..{}): {}\nStep: {}\nResult: {}\n'.format(minimum, ext - 1,l, step, getSlices(l, step))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment