Skip to content

Instantly share code, notes, and snippets.

@lukasgraf
Created August 21, 2011 14:42
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 lukasgraf/1160686 to your computer and use it in GitHub Desktop.
Save lukasgraf/1160686 to your computer and use it in GitHub Desktop.
Distributing items across columns
from math import ceil
class ColumnDistributor(list):
"""Distributes a list of items across a given number of columns.
>>> items = list('ABCDEFGHIJKLM')
>>> columns = ColumnDistributor(items)
>>> columns.distribute(4)
>>> for c in columns:
... print c
['A', 'B', 'C', 'D']
['E', 'F', 'G', 'H']
['I', 'J', 'K', 'L']
['M']
>>> columns.distribute(3)
>>> for c in columns:
... print c
['A', 'B', 'C', 'D', 'E']
['F', 'G', 'H', 'I', 'J']
['K', 'L', 'M']
If there's less items than the number of columns, the remaining columns
get represented as empty lists:
>>> columns = ColumnDistributor(list('AB'))
>>> columns.distribute(3)
>>> columns
[['A'], ['B'], []]
"""
def __init__(self, items):
super(ColumnDistributor, self).__init__(items)
self._items = items
def distribute(self, num_cols):
columns = []
# Max items any column will contain
items_per_col = int(ceil(float(len(self._items)) / num_cols))
for n in range(num_cols):
start = items_per_col * n
end = items_per_col * (n + 1)
columns.append(self._items[start:end])
# Store the resulting columns by calling superclass constructor
super(ColumnDistributor, self).__init__(columns)
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment