Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active December 17, 2015 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/5571989 to your computer and use it in GitHub Desktop.
Save joyrexus/5571989 to your computer and use it in GitHub Desktop.
Partition a list into N chunks of nearly equal size.
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) ]
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