Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Created October 31, 2020 15:58
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 hughdbrown/6e6439175dd640aac67b4481730b34e5 to your computer and use it in GitHub Desktop.
Save hughdbrown/6e6439175dd640aac67b4481730b34e5 to your computer and use it in GitHub Desktop.
Chunk items into groups of size
>>> def chunk(items, size):
... i, count = 0, len(items)
... for j in reversed(range(1, size + 1)):
... m, n = divmod(count, j)
... k = m + int(bool(n))
... yield items[i:i + k]
... i += k
... count -= k
...
>>> list(chunk(range(5), 5))
[[0], [1], [2], [3], [4]]
>>> list(chunk(range(6), 5))
[[0, 1], [2], [3], [4], [5]]
>>> list(chunk(range(7), 5))
[[0, 1], [2, 3], [4], [5], [6]]
>>> list(chunk(range(14), 5))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]
>>> list(chunk(range(15), 5))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
@hughdbrown
Copy link
Author

hughdbrown commented Oct 31, 2020

Pro: Fewer variables
Con: groups of items are in reverse order

>>> def chunk(items, size):
...     count = len(items)
...     for j in reversed(range(1, size + 1)):
...         m, n = divmod(count, j)
...         k = m + int(bool(n))
...         yield items[count - k:count]
...         count -= k
...
>>> list(chunk(range(14), 5))
[[11, 12, 13], [8, 9, 10], [5, 6, 7], [2, 3, 4], [0, 1]]

@hughdbrown
Copy link
Author

hughdbrown commented Oct 31, 2020

Pro: Simplest code
Con: The stride groups items in an unexpected way

>>> def chunk(items, size):
...     for j in range(size):
...         yield items[j::size]
...
>>> list(chunk(range(14), 5))
[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment