Read a grid by columns
A matrix is stored row by row, but a transpose report reads it column by column.
- Read columns from left to right, and within a column top to bottom.
- A ragged row contributes only the columns it actually has.
column_major(grid: list<list<int>>) → list<int>
Where you start
def column_major(grid: list[list[int]]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
column_major([[1, 2], [3, 4]]) | [1, 3, 2, 4] |
column_major([[1], [2, 3]]) | [1, 2, 3] |
column_major([[1, 2, 3], [4, 5, 6]]) | [1, 4, 2, 5, 3, 6] |
column_major([[5], [6], [7]]) | [5, 6, 7] |
Hint
For each column position, walk every row and take the value when that row is long enough.
Reference solution in Python
def column_major(grid: list[list[int]]) -> list[int]:
cols = max((len(r) for r in grid), default=0)
result = []
for c in range(cols):
for row in grid:
if c < len(row):
result.append(row[c])
return result