Turn the rows of a table into columns.
What to build
A new table made from an old one.
Requirements
- Read the table.
- Print the table with rows and columns swapped.
Input
The first line has r and c. Each of the next r lines has c whole numbers.
Output
c lines, each with r numbers separated by spaces.
Constraints
r and c are from 1 to 20.
Example
Input:
2 3
1 2 3
4 5 6
Output:
1 4
2 5
3 6
Why it works
The value at row i and column j moves to row j and column i. Looping over the columns first builds the new rows in the right order.
Examples
Example 1 · Input
2 3 1 2 3 4 5 6
Expected output
1 4 2 5 3 6
Example 2 · Input
1 2 7 8
Expected output
7 8
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The new table has c rows and r columns.
Hint 2
New row j is made of item j from each old row.
Solution
Show one correct solution (try it yourself first)
r, c = [int(x) for x in input().split()]
grid = [[int(x) for x in input().split()] for _ in range(r)]
for j in range(c):
print(" ".join(str(grid[i][j]) for i in range(r)))