Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2013 23:53
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 anonymous/4569688 to your computer and use it in GitHub Desktop.
Save anonymous/4569688 to your computer and use it in GitHub Desktop.
from collections import namedtuple
from itertools import islice
LineProperties = namedtuple('LineProperties', 'column_widths, spacing')
def get_line_properties(items, spacing=2, max_line_width=80):
item_widths = [len(item) for item in items]
num_items = len(item_widths)
column_widths = []
line_width = 0
column_size = 1
start_index, stop_index = 0, column_size
while start_index < num_items:
# This loop repeatedly adds a new column (or more specifically: a new
# column size) to an "imaginary" line. It starts with a column size
# (i.e. the number of items per column) of 1.
# Every time when max_line_width is exceeded the loop will increase the
# the column size, reset its computed values and start again with the
# first item. This is done until all items have been passed. The loop
# should then have found a sufficient configuration of column widths to
# use for LineProperties and terminates.
column_width = max(islice(item_widths, start_index, stop_index))
line_width += column_width
if line_width > max_line_width:
if not column_widths:
# Special case: first column includes an item > max_line_width
# => do not fail but just use the width limit as the result.
column_widths = [max_line_width]
break
column_widths = []
line_width = 0
column_size += 1
start_index, stop_index = 0, column_size
else:
column_widths.append(column_width)
line_width += spacing
start_index, stop_index = stop_index, stop_index + column_size
return LineProperties(column_widths, spacing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment