Typorithm · easy

Reshape, transpose and meaningful axis order

pythonnumpynumerical-computingindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Reshape, transpose and meaningful axis order

0%

Concept and contract

Change an array layout deliberately without confusing reshaping with transposition.

Reshape changes how the same sequence of elements is organized into dimensions. Transpose permutes axes. For a two-by-three matrix, reshaping its flat sequence to three-by-two does not produce the same coordinates as transposing the original matrix. The number of elements can match while the meaning of every row changes. This lesson builds an explicitly sized matrix from a flat vector and returns its transpose as an independent array.

Shape is therefore part of the data model, not cosmetic formatting. State the original row and column counts, the element traversal order and the returned axis order. NumPy cannot infer that a list represents companies by skills rather than skills by companies.

Mechanism and worked example

The worked function validates positive whole-number dimensions, checks the flat vector length against rows times columns, reshapes in ordinary C order and transposes the result.

The worked function validates positive whole-number dimensions, checks the flat vector length against rows times columns, reshapes in ordinary C order and transposes the result. It returns a copy so its output has a straightforward independent lifetime. A rectangular example is essential: many square or repeated-value examples hide the difference between reshape and transpose.

Reshape may produce a view when strides permit and may need a copy otherwise. Current NumPy can explicitly reject a requested no-copy reshape when that layout is impossible. Do not teach reshape as either always allocating or always sharing; the array layout and requested order matter.

Complete worked example

python

import numpy as np

def inspect_example(values, rows, columns):
    if type(rows) is not int or type(columns) is not int or rows < 1 or columns < 1:
        raise ValueError("expected positive dimensions")
    data = np.asarray(values, dtype=np.int64)
    if data.ndim != 1 or data.size != rows * columns:
        raise ValueError("element count does not match shape")
    matrix = data.reshape(rows, columns)
    return matrix.T.copy()
Reasoning
The worked function validates positive whole-number dimensions, checks the flat vector length against rows times columns, reshapes in ordinary C order and transposes the result. It returns a copy so its output has a straightforward independent lifetime. A rectangular example is essential: many square or repeated-value examples hide the difference between reshape and transpose. Reshape may produce a view when strides permit and may need a copy otherwise. Current NumPy can explicitly reject a requested no-copy reshape when that layout is impossible. Do not teach reshape as either always allocating or always sharing; the array layout and requested order matter.
Open in local Python playground ↗

Focused decision: context is in the complete example

python

matrix = data.reshape(rows, columns)
result = matrix.T.copy()
Focused decision
Type this short numerical decision after reading its complete context. The complete imports, array construction, validation, and result checks remain in the worked example. Typing records practice; only the downloadable computer lab executes Python.

Counterexamples and common mistakes

The controlled counterexample reshapes directly to the reversed dimensions instead of transposing.

The controlled counterexample reshapes directly to the reversed dimensions instead of transposing. Its output has the expected shape but incorrect element positions. This demonstrates why separate shape and value checks are both needed. Flattening a transposed non-contiguous array can also require copying, even when the original array was contiguous.

Do not use resize as a synonym for reshape. Repetition, truncation and in-place size changes have different semantics and ownership constraints. A reshape failure is a useful signal that the declared dimensions do not describe the supplied observations; automatically padding missing measurements would change the data.

Controlled mistake: inspect the failing numerical contract

python

import numpy as np

def inspect_example(values, rows, columns):
    if type(rows) is not int or type(columns) is not int or rows < 1 or columns < 1:
        raise ValueError("expected positive dimensions")
    data = np.asarray(values, dtype=np.int64)
    if data.ndim != 1 or data.size != rows * columns:
        raise ValueError("element count does not match shape")
    matrix = data.reshape(rows, columns)
    return data.reshape(columns, rows).copy()
Reasoning
The controlled counterexample reshapes directly to the reversed dimensions instead of transposing. Its output has the expected shape but incorrect element positions. This demonstrates why separate shape and value checks are both needed. Flattening a transposed non-contiguous array can also require copying, even when the original array was contiguous. Do not use resize as a synonym for reshape. Repetition, truncation and in-place size changes have different semantics and ownership constraints. A reshape failure is a useful signal that the declared dimensions do not describe the supplied observations; automatically padding missing measurements would change the data.
Open in local Python playground ↗

Independent practice

Keep the declared input matrix shape, but return that matrix unchanged in axis order instead of transposing it.

Keep the declared input matrix shape, but return that matrix unchanged in axis order instead of transposing it. Retain the independent output and every size check. This is a small operation-choice task: replace the axis permutation rather than adjusting the expected values to fit an accidental layout.

Trace the six coordinates for a two-by-three example. Then test a one-by-three example and a mismatched length. The new output should be two-by-three in the first case and one-by-three in the second; invalid declared dimensions should still fail before the return.

Step 1: Return the declared matrix without transposing its axes. Step 2: Retain the working imports, input validation and array shapes. Change the stated policy, run the supplied practice cases, then explain the newly accepted or rejected boundary.

Practice starter: solve before reading the solution

python

import numpy as np

def inspect_example(values, rows, columns):
    if type(rows) is not int or type(columns) is not int or rows < 1 or columns < 1:
        raise ValueError("expected positive dimensions")
    data = np.asarray(values, dtype=np.int64)
    if data.ndim != 1 or data.size != rows * columns:
        raise ValueError("element count does not match shape")
    matrix = data.reshape(rows, columns)
    return matrix.T.copy()

# Independent task: Return the declared matrix without transposing its axes.
Reasoning
Return the declared matrix without transposing its axes.
Open in local Python playground ↗
  • Hint 1: The reshape already establishes the requested input rows and columns.
  • Hint 2: Return matrix.copy() instead of permuting its axes.

Solution, tests and trade-offs

The changed return copies matrix directly.

The changed return copies matrix directly. It preserves row-major construction and the original row/column meaning. Tests use both rectangular dimensions and a single row to reject an implementation that happens to work only when swapping axes is invisible. The expected dtype remains int64, independent of a platform default integer width.

This exercise does not claim that a copy is always required after transposition. It intentionally gives the learner a simple ownership contract while learning the axis transformation. In measured production code, a documented view can avoid a copy if the consumer supports its strides and shared lifetime.

Practice solution and acceptance checks

python

import numpy as np

def inspect_example(values, rows, columns):
    if type(rows) is not int or type(columns) is not int or rows < 1 or columns < 1:
        raise ValueError("expected positive dimensions")
    data = np.asarray(values, dtype=np.int64)
    if data.ndim != 1 or data.size != rows * columns:
        raise ValueError("element count does not match shape")
    matrix = data.reshape(rows, columns)
    return matrix.copy()
Reasoning
The changed return copies matrix directly. It preserves row-major construction and the original row/column meaning. Tests use both rectangular dimensions and a single row to reject an implementation that happens to work only when swapping axes is invisible. The expected dtype remains int64, independent of a platform default integer width. This exercise does not claim that a copy is always required after transposition. It intentionally gives the learner a simple ownership contract while learning the axis transformation. In measured production code, a documented view can avoid a copy if the consumer supports its strides and shared lifetime.
Open in local Python playground ↗

Interview reasoning and next step

Explain reshape versus transpose with a rectangular matrix and show their different results.

Explain reshape versus transpose with a rectangular matrix and show their different results. Describe what -1 can infer in a shape and why it does not authorize inventing missing elements. Discuss how strides allow some transformations without moving the underlying data. These concepts also appear in tensor libraries, but a familiar method name does not establish identical behavior in every library.

Type the short reshape-and-transpose sequence, then reproduce it from the required output shape. Use the native questions to reason through coordinates. Next, combine arrays with different compatible shapes and make every implicit broadcast axis explicit.

Optional stretch — after the core task works: Add one independently reasoned boundary case and explain its expected value before running it.

Computer practice: https://applydjinn.com/typorithm/numpy-lab-20261106.zip. Install pinned dependencies in an isolated Python environment. Run verify.py, then change the working exercise baseline and run --practice np-shapes. The real NumPy arrays, numerical contracts, random state checks and temporary numeric files use owned fixtures only. No production database, feed, account or paid service is used. This lab executes Python; the PC typing trainer and native reading progress do not execute it.

Change an array layout deliberately without confusing reshaping with transposition.