Against the Grain
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
A metrics export comes back as a grid of equal-length rows, one row per day and one column per metric. Reorient it so each metric's column becomes its own row, and return an empty list when grid has no rows or its rows are empty.
Turn the grid on its side and let every column stand up as a row.
Example 1
Input:
grid = [[1,2,3],[4,5,6]]
Output:
[[1,4],[2,5],[3,6]]
Example 2
Input:
grid = [[1,2],[3,4],[5,6]]
Output:
[[1,3,5],[2,4,6]]
Worked solution and explanation
Metric columns become rows
This is a matrix transpose: the value at row r, column c of the input lands at row c, column r of the output. The first example has 2 days and 3 metrics, so it comes back as 3 rows of 2 values, and [1, 4] is the first metric read down both days. You meet the same shape whenever per-day records have to become per-metric series, or any rectangular block has to be read along its other axis.
Let the output shape pick the loops
Step 1: Guard the empty export
grid[0] raises IndexError on an empty list, so not grid is checked before anything reads the first row. not grid[0] covers an export whose days carry no metrics, and both cases return [].
Step 2: Read the shape once
rows is the number of days and cols is the number of metrics, taken from grid[0] because the statement promises equal-length rows. The output will hold cols rows of rows values each.
Step 3: Outer loop over what you emit
Each output row is one metric, so the outer loop walks c over range(cols) and starts a fresh new_row. The inner loop walks r over the days and appends grid[r][c]. The read still indexes row first; the only thing that flips is which loop sits outside.
def transpose(grid: list) -> list:
if not grid or not grid[0]:
return []
rows = len(grid)
cols = len(grid[0])
result = []
for c in range(cols):
new_row = []
for r in range(rows):
new_row.append(grid[r][c])
result.append(new_row)
return resultThe outer index runs over input columns, so each pass builds exactly one output row.
What the habitual nesting returns
Most grid code you have written loops over rows on the outside, and that habit is the easy mistake here. The program below looks like it does real work, and it runs without error on every input.
def transpose(grid):
if not grid or not grid[0]:
return []
result = []
for r in range(len(grid)):
new_row = []
for c in range(len(grid[0])):
new_row.append(grid[r][c])
result.append(new_row)
return resultOn [[1, 2, 3], [4, 5, 6]] this returns [[1, 2, 3], [4, 5, 6]]: a copy of the input with nothing reoriented.
Letting zip do the pairing
zip(*grid) passes each day as its own argument. zip then groups the first value from every day, followed by the second value from every day, until the days run out. Those groups are the metric columns, already in output order.
def transpose(grid):
return [list(col) for col in zip(*grid)]zip yields tuples, so list(col) keeps the output a list of lists. An empty grid and a grid of empty rows both produce [] with no guard.
Common follow-up questions
- What happens if one day's row is shorter or longer than the first?
The loop version raises
IndexErroron a short row and silently drops the extra values of a long one, whilezipcuts the output at the shortest row's length. Real exports lose trailing fields, so decide up front whether a ragged row fails the load or gets padded withitertools.zip_longest. - Can you transpose the export as a stream, without holding all of it?
No output row is complete until the last day has arrived, because every metric's row needs one value from each day. The whole input has to be held or spilled to disk first, so row-to-column conversions of large files run as a buffered batch step.
- Which tests would you write for this function?
Test a wide grid and a tall grid, then the edge shapes: a single row, a single column,
[]and[[]]. The 2 non-square shapes catch swapped bounds, and the empty ones catch an unguardedgrid[0]. A square grid passes even with the loop bounds swapped, so it proves little by itself.