Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ethansocal/aaf14e85b14ed144b73a0d40f3c82bf2 to your computer and use it in GitHub Desktop.
Save ethansocal/aaf14e85b14ed144b73a0d40f3c82bf2 to your computer and use it in GitHub Desktop.
This was my solution that I made for the Python Discord Summer Code Jam 2020 Qualifier. It isn't the best, but it works :)
from typing import Any, List, Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
"""
hi
:param rows: 2D list containing objects that have a single-line representation (via `str`).
All rows must be of the same length.
:param labels: List containing the column labels. If present, the length must equal to that of each row.
:param centered: If the items should be aligned to the center, else they are left aligned.
:return: A table representing the rows passed in.
"""
# Calculate row lengths
row_lengths = []
for i, row in enumerate(rows):
for i2, item in enumerate(row):
try:
if row_lengths[i2] < len(str(item)):
row_lengths[i2] = len(str(item))
except IndexError:
row_lengths.append(len(str(item)))
if labels is not None:
for i, label in enumerate(labels):
try:
if row_lengths[i] < len(str(label)):
row_lengths[i] = len(str(label))
except IndexError:
row_lengths.append(len(str(label)))
# Calculate the column underlines
column_underlines = []
for i, row in enumerate(rows[0]):
column_underlines.append("─" * (row_lengths[i] + 2))
# Create the table top
table = f"┌{'┬'.join(column_underlines)}┐"
# Add labels (if exists)
if labels is not None:
labels_list = []
if not centered:
for i, label in enumerate(labels):
labels_list.append(str(label) + (" " * (row_lengths[i] - len(str(label)))))
else:
for i, label in enumerate(labels):
offset_correction = 0
if row_lengths[i] % 2 != len(str(label)) % 2:
offset_correction = 1
labels_list.append((" " * ((row_lengths[i] - len(str(label))) // 2)) + str(label) + (" " * (((row_lengths[i] - len(str(label))) // 2) + offset_correction)))
table += f"\n{' │ '.join(labels_list)} │"
table += f"\n{'┼'.join(column_underlines)}┤"
# Add table data
for row_index, data_row in enumerate(rows):
data_list = []
if not centered:
for i, row in enumerate(data_row):
data_list.append(str(row) + (" " * (row_lengths[i] - len(str(row)))))
else:
for i, row in enumerate(data_row):
offset_correction = 0
if row_lengths[i] % 2 != len(str(row)) % 2:
offset_correction = 1
data_list.append((" " * ((row_lengths[i] - len(str(row))) // 2)) + str(row) + (" " * (((row_lengths[i] - len(str(row))) // 2) + offset_correction)))
table += f"\n{' │ '.join(data_list)} │"
if row_index == len(rows) - 1:
table += f"\n{'┴'.join(column_underlines)}┘"
return table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment