Same Readings, New Tray

Data with PythonMedium+20 XP+20

Same Readings, New Tray

A data logger stores its readings as a grid, but every analysis wants them laid out differently. Rather than retype them, you write a helper that lays the same readings into a new grid.

Task: write relayout(grid, rows, cols):

  1. Read the values of grid in reading order: the first row left to right, then the second row, and so on.
  2. Lay them into a new grid of rows rows and cols columns, filling the first row left to right, then the next row, and so on.
  3. Return the new grid as a list of lists.

Either rows or cols may be -1, meaning "whatever number makes this fit".

If the new layout can't hold exactly the readings — with nothing left over and no gaps — return None instead. That includes the case where rows and cols are both -1, since then more than one layout would fit.

Apart from -1, rows and cols are always positive whole numbers. grid has at least one value and all its rows are the same length.

Example

Examples

grid = [[1, 2, 3], [4, 5, 6]]
rows = 3
cols = 2
returns [[1, 2], [3, 4], [5, 6]]
grid = [[1, 2, 3], [4, 5, 6]]
rows = 4
cols = 2
returns None

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run