Typorithm · easy

Arrays, dimensions and an explicit shape contract

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

Arrays, dimensions and an explicit shape contract

0%

Concept and contract

Construct a rectangular numerical array and distinguish shape, rank, size and Python container length.

A Python list is a container of references, while an ndarray describes a typed block through dimensions, strides and a dtype. For a matrix with two rows and three columns, ndim is two, shape is (2, 3), and size is six. len answers only the size of the first axis. These are different questions. The first contract in this course accepts a non-empty rectangular matrix of finite measurements and returns an independent float64 array.

Axes are positions in shape, not business labels. Write down whether rows represent companies, observations or days before computing anything. NumPy does not attach that meaning to axis zero for you. A successful conversion is not evidence that the selected population, units or column order are correct.

Mechanism and worked example

Import NumPy as np, convert the supplied rows with an explicit float64 dtype, and inspect ndim before using two-axis indexing.

Import NumPy as np, convert the supplied rows with an explicit float64 dtype, and inspect ndim before using two-axis indexing. The worked function rejects scalars, vectors, empty dimensions and non-finite values. A copy makes the returned data independent even when a caller supplies an array rather than a list. The lab checks the actual ndarray type, exact shape, dtype and values, so returning a visually similar nested list does not pass.

Start by tracing a two-by-three example on paper. Each pair of coordinates selects one scalar. The shape belongs to the complete array, while each row view has its own one-dimensional shape. No model training or advanced mathematics is required to establish this boundary.

Complete worked example

python

import numpy as np

def inspect_example(rows):
    data = np.array(rows, dtype=np.float64, copy=True)
    if data.ndim != 2 or 0 in data.shape:
        raise ValueError("a non-empty matrix is required")
    if not np.isfinite(data).all():
        raise ValueError("measurements must be finite")
    return data
Reasoning
Import NumPy as np, convert the supplied rows with an explicit float64 dtype, and inspect ndim before using two-axis indexing. The worked function rejects scalars, vectors, empty dimensions and non-finite values. A copy makes the returned data independent even when a caller supplies an array rather than a list. The lab checks the actual ndarray type, exact shape, dtype and values, so returning a visually similar nested list does not pass. Start by tracing a two-by-three example on paper. Each pair of coordinates selects one scalar. The shape belongs to the complete array, while each row view has its own one-dimensional shape. No model training or advanced mathematics is required to establish this boundary.
Open in local Python playground ↗

Focused decision: context is in the complete example

python

import numpy as np

data = np.array([[1, 2], [3, 4]], dtype=np.float64)
if data.ndim != 2:
    raise ValueError("expected a matrix")
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

A frequent mistake is to flatten input immediately because a flat sequence is easier to print.

A frequent mistake is to flatten input immediately because a flat sequence is easier to print. That silently loses the row boundary and can mix different companies in later calculations. A second mistake is treating a ragged list as a rectangular table; ordinary numeric construction rejects unequal row lengths. Explicit object arrays solve a different problem and are outside this contract.

Do not use the fact that values print as integers to infer an integer dtype. The selected dtype is part of the storage and arithmetic contract. The controlled counterexample preserves every numerical value but changes the shape, demonstrating why value-only assertions are insufficient.

Controlled mistake: inspect the failing numerical contract

python

import numpy as np

def inspect_example(rows):
    data = np.array(rows, dtype=np.float64, copy=True)
    if data.ndim != 2 or 0 in data.shape:
        raise ValueError("a non-empty matrix is required")
    if not np.isfinite(data).all():
        raise ValueError("measurements must be finite")
    return data.ravel()
Reasoning
A frequent mistake is to flatten input immediately because a flat sequence is easier to print. That silently loses the row boundary and can mix different companies in later calculations. A second mistake is treating a ragged list as a rectangular table; ordinary numeric construction rejects unequal row lengths. Explicit object arrays solve a different problem and are outside this contract. Do not use the fact that values print as integers to infer an integer dtype. The selected dtype is part of the storage and arithmetic contract. The controlled counterexample preserves every numerical value but changes the shape, demonstrating why value-only assertions are insufficient.
Open in local Python playground ↗

Independent practice

Keep the same non-empty rectangular matrix contract, but return float32 instead of float64.

Keep the same non-empty rectangular matrix contract, but return float32 instead of float64. Change only the explicitly selected dtype. Preserve the number of rows and columns, the finite-value check and the independent output. The supplied small integer-valued fixtures are exactly representable in either dtype, so their values stay the same while the representation changes.

Before editing, predict which acceptance property should change and which should remain fixed. This is a deliberately small first task: no new reduction, concatenation, broadcasting rule or library method is needed. Find the dtype argument in the constructor and use the same array-creation pattern you already read.

Step 1: Return the validated matrix as float32, preserving shape and independent ownership. Step 2: Retain the working constructor and validation. Change only the explicit dtype, then compare dtype, shape and values.

Practice starter: solve before reading the solution

python

import numpy as np

def inspect_example(rows):
    data = np.array(rows, dtype=np.float64, copy=True)
    if data.ndim != 2 or 0 in data.shape:
        raise ValueError("a non-empty matrix is required")
    if not np.isfinite(data).all():
        raise ValueError("measurements must be finite")
    return data

# Independent task: Return the validated matrix as float32, preserving shape and independent ownership.
Reasoning
Return the validated matrix as float32, preserving shape and independent ownership.
Open in local Python playground ↗
  • Hint 1: The dtype argument owns the element representation.
  • Hint 2: Use dtype=np.float32 in the same np.array constructor.

Solution, tests and trade-offs

The solution changes the constructor dtype to np.float32.

The solution changes the constructor dtype to np.float32. The returned ndarray keeps the exact original matrix shape and the same small fixture values. Acceptance checks inspect dtype separately from values, so a float64 array or nested list with identical printed numbers cannot pass the changed contract. Invalid dimensions and ragged rows are still rejected.

Float32 uses fewer element bytes and has less precision and a smaller numerical range than float64. This exercise does not claim that either representation is universally better. It makes an explicit storage choice observable on simple values before the next lesson explores fixed-width arithmetic, promotion and overflow in greater detail.

Practice solution and acceptance checks

python

import numpy as np

def inspect_example(rows):
    data = np.array(rows, dtype=np.float32, copy=True)
    if data.ndim != 2 or 0 in data.shape:
        raise ValueError("a non-empty matrix is required")
    if not np.isfinite(data).all():
        raise ValueError("measurements must be finite")
    return data
Reasoning
The solution changes the constructor dtype to np.float32. The returned ndarray keeps the exact original matrix shape and the same small fixture values. Acceptance checks inspect dtype separately from values, so a float64 array or nested list with identical printed numbers cannot pass the changed contract. Invalid dimensions and ragged rows are still rejected. Float32 uses fewer element bytes and has less precision and a smaller numerical range than float64. This exercise does not claim that either representation is universally better. It makes an explicit storage choice observable on simple values before the next lesson explores fixed-width arithmetic, promotion and overflow in greater detail.
Open in local Python playground ↗

Interview reasoning and next step

For an interview, explain ndim, shape and size using a concrete matrix, then identify which axis represents the observations.

For an interview, explain ndim, shape and size using a concrete matrix, then identify which axis represents the observations. Describe why validation precedes indexing and why a returned copy can matter to its caller. Explain which information flattening discards. These answers should refer to the actual returned object and the failing case, rather than only repeating method names.

On the computer, type the short array construction and shape check, then reconstruct it with the reference hidden. In the app, reason about shape and rejected input through the questions. The downloadable lab is where the complete function actually executes. Next, inspect how the dtype changes arithmetic and memory requirements.

Optional stretch — after the core task works: Compare .nbytes for the same shape in float32 and float64, then explain why fewer bytes do not guarantee adequate numerical precision.

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-arrays. 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.

Construct a rectangular numerical array and distinguish shape, rank, size and Python container length.