Transpose a matrix and print it exactly as NumPy prints an integer array.
What to build
A program that prints the shape and contents of a matrix's transpose.
Requirements
- Print
shape (C, R), the shape of the transpose. - Then print the transpose in NumPy's format:
[[before the first row, a space and[before each later row, numbers right-aligned to the widest number in the array and separated by one space, and]]after the last row.
Input
Line 1: r and c. Then r lines of c whole numbers.
Output
1 + c lines.
Constraints
1 ≤ r, c ≤ 10; |x| ≤ 10⁵.
Example
Input:
2 3
1 2 3
4 5 6
Output:
shape (3, 2)
[[1 4]
[2 5]
[3 6]]
Why it works
Row i of the transpose is column i of the original, which is exactly what zip(*m) produces, and printing with one shared width reproduces NumPy's aligned columns.
Examples
Example 1 · Input
2 3 1 2 3 4 5 6
Expected output
shape (3, 2) [[1 4] [2 5] [3 6]]
Example 2 · Input
1 3 7 -8 9
Expected output
shape (3, 1) [[ 7] [-8] [ 9]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
zip(*m) gives the columns of m, which are the rows of m.T.
Hint 2
NumPy pads every number to the width of the widest one in the whole array.
Solution
Show one correct solution (try it yourself first)
def fmt2(m):
w = max(len(str(v)) for row in m for v in row)
rows = ["[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in m]
return "[" + "\n ".join(rows) + "]"
r, c = map(int, input().split())
m = [[int(x) for x in input().split()] for _ in range(r)]
t = [list(col) for col in zip(*m)]
print(f"shape ({c}, {r})")
print(fmt2(t))