-
Notifications
You must be signed in to change notification settings - Fork 25
/
tabulator3.py
executable file
·89 lines (73 loc) · 2.65 KB
/
tabulator3.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import sys
if sys.version_info[:2] < (3, 2):
from xml.sax.saxutils import escape
else:
from html import escape
WINNERS = ("Nikolai Andrianov", "Matt Biondi", "Bjørn Dæhlie",
"Birgit Fischer", "Sawao Kato", "Larisa Latynina", "Carl Lewis",
"Michael Phelps", "Mark Spitz", "Jenny Thompson")
def main():
htmlLayout = Layout(html_tabulator)
for rows in range(2, 6):
print(htmlLayout.tabulate(rows, WINNERS))
textLayout = Layout(text_tabulator)
for rows in range(2, 6):
print(textLayout.tabulate(rows, WINNERS))
class Layout:
def __init__(self, tabulator):
self.tabulator = tabulator
def tabulate(self, rows, items):
return self.tabulator(rows, items)
def html_tabulator(rows, items):
columns, remainder = divmod(len(items), rows)
if remainder:
columns += 1
column = 0
table = ['<table border="1">\n']
for item in items:
if column == 0:
table.append("<tr>")
table.append("<td>{}</td>".format(escape(str(item))))
column += 1
if column == columns:
table.append("</tr>\n")
column %= columns
if table[-1][-1] != "\n":
table.append("</tr>\n")
table.append("</table>\n")
return "".join(table)
def text_tabulator(rows, items):
columns, remainder = divmod(len(items), rows)
if remainder:
columns += 1
remainder = (rows * columns) - len(items)
if remainder == columns:
remainder = 0
column = columnWidth = 0
for item in items:
columnWidth = max(columnWidth, len(item))
columnDivider = ("-" * (columnWidth + 2)) + "+"
divider = "+" + (columnDivider * columns) + "\n"
table = [divider]
for item in items + (("",) * remainder):
if column == 0:
table.append("|")
table.append(" {:<{}} |".format(item, columnWidth))
column += 1
if column == columns:
table.append("\n")
column %= columns
table.append(divider)
return "".join(table)
if __name__ == "__main__":
main()