Drill

ProblemsPython › data

Read a grid by columns

easydataPython

A matrix is stored row by row, but a transpose report reads it column by column.

column_major(grid: list<list<int>>) → list<int>

Solve it in the editor →

Where you start

def column_major(grid: list[list[int]]) -> list[int]:
    

Worked examples

CallResult
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

The same problem in another language

More data problems in Python