-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.py
70 lines (54 loc) · 1.82 KB
/
table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# python version 3.8 required
from sys import stdin as s
from sys import stdout
def add_table_headers_to_list(line: str) -> list:
headers = []
for header in line.split("] "):
header = header.strip().replace("]", "").replace("[", "")
headers.append(header.center(4))
return headers
def add_data_to_rows(data: list) -> list:
data_by_rows = []
for row in data:
data_by_rows.append(row.rstrip().split(" "))
return data_by_rows
def create_table(headers: list, data: list) -> str:
width = len(headers)
for word in headers:
width += len(word)
width_table = [len(word) for word in headers]
top_line = '.'
for width in width_table:
top_line += f'{"-"*width}+'
top_line = f'{top_line[:-1]}.'
mid_delimiter = "|"
for width in width_table:
mid_delimiter += f'{"-" * width}+'
mid_delimiter = f'{mid_delimiter[:-1]}|'
bottom_line = '\''
for width in width_table:
bottom_line += f'{"-"*width}+'
bottom_line = f'{bottom_line[:-1]}\''
table = f'{top_line}\n'
# add the headers
for header in headers:
table += f'|{header}'
table = f'{table}|'
table += f'\n{mid_delimiter}\n|'
# add the data
for row in data:
for i in range(0,len(row)):
table += f'{row[i].center(width_table[i])}|'
table += f'\n{mid_delimiter}\n|'
# clean up the bottom
table = table[:(len(table) - len(mid_delimiter) -2)]
# add the bottom line
table += f'{bottom_line}'
return table
data = s.read().splitlines()
if table_headers := data.pop(0): # need python 3.8 for walrus use :=
table_headers = add_table_headers_to_list(table_headers)
data_by_rows = add_data_to_rows(data)
stdout.write(create_table(table_headers, data_by_rows))
else:
stdout.write("ERROR NO INPUT DATA")