Skip to content

Instantly share code, notes, and snippets.

@salt-die
Created July 4, 2021 18:18
Show Gist options
  • Save salt-die/418c56cdbc803d7d18aadb4fd603d082 to your computer and use it in GitHub Desktop.
Save salt-die/418c56cdbc803d7d18aadb4fd603d082 to your computer and use it in GitHub Desktop.
salt's official solution to codejam 21
def _make_row(separators, entries):
"""A string representation of a single row in a table.
"""
left, middle, right = separators
return f'{left}{middle.join(entries)}{right}'
CENTERED = ' {:^{width}} '
LEFT_ALIGNED = ' {:<{width}} '
def make_table(rows, labels=None, centered=False):
"""A string representation of a pretty, aligned table.
"""
# Transpose rows into columns.
it = zip(labels, *rows) if labels else zip(*rows)
columns = list(map(list, it))
# Strings in each column made same length and centered if needed.
formatting = CENTERED if centered else LEFT_ALIGNED
for i, column in enumerate(columns):
column_width = max(map(len, column))
columns[i] = [formatting.format(item, width=column_width) for item in column]
rows = [_make_row('│││', row) for row in zip(*columns)] # Transpose columns to rows again and join the entries.
horizontals = tuple('─' * len(column[0]) for column in columns) # Horizontal sections for border rows.
top_border = _make_row('┌┬┐', horizontals)
rows.insert(0, top_border)
if labels:
label_border_bottom = _make_row('├┼┤', horizontals)
rows.insert(2, label_border_bottom)
bottom_border = _make_row('└┴┘', horizontals)
rows.append(bottom_border)
return '\n'.join(rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment