forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolumnize2.py
More file actions
37 lines (27 loc) · 1.01 KB
/
Copy pathcolumnize2.py
File metadata and controls
37 lines (27 loc) · 1.01 KB
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
from typing import Sequence, List, Tuple, TypeVar
T = TypeVar('T')
def columnize(sequence: Sequence[T], num_columns: int = 0) -> List[Tuple[T, ...]]:
if num_columns == 0:
num_columns = round(len(sequence) ** .5)
num_rows, reminder = divmod(len(sequence), num_columns)
num_rows += bool(reminder)
return [tuple(sequence[i::num_rows]) for i in range(num_rows)]
def demo() -> None:
nato = ('Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India'
' Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo'
' Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu'
).split()
for line in columnize(nato):
for word in line:
print(f'{word:15}', end='')
print()
print()
for length in range(2, 21, 6):
values = list(range(1, length + 1))
for row in columnize(values):
for cell in row:
print(f'{cell:5}', end='')
print()
print()
if __name__ == '__main__':
demo()