Last active
December 17, 2015 07:19
-
-
Save joyrexus/5571989 to your computer and use it in GitHub Desktop.
Partition a list into N chunks of nearly equal size.
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 chunk(L, n): | |
''' | |
Partition L into n chunks using every item in L and | |
such that the resulting chunks differ in size by at | |
most one element. | |
>>> L = ['a', 'b', 'c', 'd'] | |
['a', 'b', 'c', 'd'] | |
>>> chunk(L, 2) | |
[['a', 'b'], ['c', 'd']] | |
>>> chunk(L, 3) | |
[['a'], ['b', 'c'], ['d']] | |
>>> chunk(L, 4) | |
[['a'], ['b'], ['c'], ['d']] | |
>>> chunk(L, 5) | |
[['a'], ['b'], [], ['c'], ['d']] | |
''' | |
size = len(L) / float(n) | |
I = lambda i: int(round(i)) | |
return [ L[I(size*i):I(size*(i+1))] for i in xrange(n) ] |
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 parts(L, n): | |
''' | |
Partition L into n parts using every item in L | |
and such that the resulting chunks differ in size | |
by at most one element. | |
HT to [Mark Dickinson](http://stackoverflow.com/a/2660138/546630). | |
>>> L = ['a', 'b', 'c', 'd'] | |
['a', 'b', 'c', 'd'] | |
>>> parts(L, 2) | |
[['a', 'b'], ['c', 'd']] | |
>>> parts(L, 3) | |
[['a', 'b'], ['c'], ['d']] | |
>>> parts(L, 4) | |
[['a'], ['b'], ['c'], ['d']] | |
>>> parts(L, 5) | |
[['a'], ['b'], ['c'], ['d'], []] | |
''' | |
q, r = divmod(len(L), n) | |
I = [q*i + min(i, r) for i in xrange(n+1)] | |
return [L[I[i]:I[i+1]] for i in xrange(n)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment