JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python NUMPY (with PREREQUISITES: vectors, matrices, basic statistics): 17 practice problems

UNIT 3 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise NUMPY (with PREREQUISITES: vectors, matrices, basic statistics) nowAll topics

Theory: NUMPY (with PREREQUISITES: vectors, matrices, basic statistics) in Python

PREREQUISITE THEORY — the maths NumPy (and AI) is built on
---------------------------------------------------------
* VECTOR = ordered list of numbers [3, 4].  MATRIX = grid of numbers with ROWS x COLUMNS (shape).
* DOT PRODUCT of two equal-length vectors: multiply pairwise, then add.
      [1, 2, 3] · [4, 5, 6] = 1*4 + 2*5 + 3*6 = 32       (a neuron computes exactly this!)
* MATRIX MULTIPLICATION A (m x n) @ B (n x p) -> (m x p): the INNER sizes must match.
  Entry [i][j] = dot product of ROW i of A with COLUMN j of B.
* STATISTICS
      mean     = sum / count
      median   = middle value of the SORTED data (average of the 2 middle values if count is even)
      variance = mean of squared deviations from the mean;  std = sqrt(variance)
                 (population: divide by n   ·   sample: divide by n - 1 — NumPy's default is n)
      z-score  = (x - mean) / std   "how many stds away from average"
      min-max normalization = (x - min) / (max - min)  -> values in [0, 1]

NUMPY THEORY
------------
* ndarray: N-dimensional array, ONE dtype, contiguous memory -> operations run in C, no Python
  loop ("VECTORIZATION") -> 10-100x faster than lists.   import numpy as np
* CREATE  np.array([1, 2]), np.zeros((2, 3)), np.ones(3), np.full((2, 2), 7), np.eye(3),
          np.arange(0, 10, 2), np.linspace(0, 1, 5), rng = np.random.default_rng(0); rng.random(3)
* ATTRIBUTES  a.shape (rows, cols)  a.ndim  a.size  a.dtype   a.astype(float)
* INDEXING  a[0], a[-1], a[1:3]; 2-D: m[row, col], m[0] (row 0), m[:, 1] (column 1), m[::2, ::2]
            fancy: a[[0, 2]]     boolean MASK: a[a > 5]  (& | ~ with parentheses: a[(a > 1) & (a < 5)])
* ELEMENT-WISE maths: + - * / ** on arrays, np.sqrt, np.exp, np.log, np.abs, np.round(a, 2)
* BROADCASTING: shapes are stretched to match: (3, 3) + (3,) adds the row to every row;
  (n, 1) - (1, n) -> (n, n) grid of all pairwise differences.
* AGGREGATE  sum mean median std var min max argmin argmax cumsum — with axis:
      axis=0 -> down the rows -> one result PER COLUMN;   axis=1 -> across -> one PER ROW
* RESHAPE  a.reshape(2, 3) (-1 = infer), a.T (transpose), a.flatten(), np.vstack / np.hstack / np.concatenate
* np.where(cond, x, y)   np.clip(a, lo, hi)   np.unique(a, return_counts=True)   np.argsort(a)
* LINEAR ALGEBRA  a @ b (matmul), np.dot, np.linalg.inv, np.linalg.det, np.linalg.solve(A, b)
* Slices are VIEWS (share memory) — use .copy() if you'll modify.

17 NUMPY (with PREREQUISITES: vectors, matrices, basic statistics) practice problems

1. PREREQ — Mean, Median, Std by Hand (no imports)

Easy1 way to solve
📤 OUTPUT: return a tuple, e.g. (5.0, 4.5, 2.0). Use `return`, not print().
Return (mean, median, population_std) each rounded to 2.
    stats_pure([2, 4, 4, 4, 5, 5, 7, 9]) -> (5.0, 4.5, 2.0)
Solve “PREREQ — Mean, Median, Std by Hand (no imports)” in your browser →

2. PREREQ — Dot Product by Hand

Easy2 ways to solve
📤 OUTPUT: return an int, e.g. 32. Use `return`, not print().
    dot_pure([1, 2, 3], [4, 5, 6]) -> 32
Solve “PREREQ — Dot Product by Hand” in your browser →

3. PREREQ — Matrix Multiplication by Hand (triple loop)

Medium2 ways to solve
📤 OUTPUT: return a list of lists, e.g. [[19, 22], [43, 50]]; RAISE ValueError for bad shapes. Use `return`, not print().
    matmul_pure([[1, 2], [3, 4]], [[5, 6], [7, 8]]) -> [[19, 22], [43, 50]]
Raise ValueError if the inner dimensions don't match.
Solve “PREREQ — Matrix Multiplication by Hand (triple loop)” in your browser →

4. Seat Numbers Grid — arange + reshape

Easy1 way to solve
📤 OUTPUT: return a NumPy array, e.g. [[0, 1, 2], [3, 4, 5], [6, 7, 8]]. Use `return`, not print().
Return an n x n array numbered 0 .. n*n-1 row by row.
    grid(3) -> [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Solve “Seat Numbers Grid — arange + reshape” in your browser →

5. Checkerboard — slicing with steps

Medium2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [[0, 1, 0], [1, 0, 1], [0, 1, 0]]. Use `return`, not print().
n x n int array, top-left 0, alternating 0/1 like a chess board.
    checkerboard(3) -> [[0, 1, 0], [1, 0, 1], [0, 1, 0]]
Ways: zeros + a[1::2, ::2] = 1 + a[::2, 1::2] = 1  ·  (np.indices sum) % 2
Solve “Checkerboard — slicing with steps” in your browser →

6. Exam Z-Scores — vectorized maths

Easy1 way to solve
📤 OUTPUT: return a NumPy array, e.g. [-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0]. Use `return`, not print().
Real world: "How far above the class average was I?"  (x - mean) / std, rounded to 2.
    z_scores(np.array([2, 4, 4, 4, 5, 5, 7, 9])) -> [-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0]
Solve “Exam Z-Scores — vectorized maths” in your browser →

7. Cap Sensor Outliers — np.clip

Easy2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [0, 3, 100, 50]. Use `return`, not print().
    cap_outliers(np.array([-5, 3, 120, 50]), 0, 100) -> [0, 3, 100, 50]
Solve “Cap Sensor Outliers — np.clip” in your browser →

8. Average per Subject — axis

Easy1 way to solve
📤 OUTPUT: return a NumPy array, e.g. [80.0, 75.0]. Use `return`, not print().
marks: 2-D array, rows = students, columns = subjects. Return column means rounded to 2.
    subject_averages(np.array([[80, 90], [70, 60], [90, 75]])) -> [80.0, 75.0]
Solve “Average per Subject — axis” in your browser →

9. Top-N Products by Sales — argsort

Medium2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [2, 3]. Use `return`, not print().
Return the indices of the n largest values, largest first.
    top_n_indices(np.array([5, 1, 9, 7]), 2) -> [2, 3]
Solve “Top-N Products by Sales — argsort” in your browser →

10. Clean Negative Readings — np.where / boolean mask

Easy3 ways to solve
📤 OUTPUT: return a NEW array (don't modify the input). Use `return`, not print().
    replace_negatives(np.array([3, -1, 4, -5])) -> [3, 0, 4, 0]
Return a NEW array (don't modify the input).
Solve “Clean Negative Readings — np.where / boolean mask” in your browser →

11. Distance Matrix — broadcasting

Hard2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [[0.0, 5.0, 10.0], [5.0, 0.0, 5.0], [10.0, 5.0…. Use `return`, not print().
Real world: Delivery app: distance between every pair of stops.
points: (n, 2) array. Return the (n, n) Euclidean distance matrix rounded to 2.
    pairwise_distances(np.array([[0, 0], [3, 4], [6, 8]])) -> [[0, 5, 10], [5, 0, 5], [10, 5, 0]]
Hint: diff = points[:, None, :] - points[None, :, :]  ->  shape (n, n, 2)
Solve “Distance Matrix — broadcasting” in your browser →

12. Rolling Mean Without a Loop — cumsum or np.convolve

Medium2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [1.5, 2.5, 3.5, 4.5]. Use `return`, not print().
    rolling_mean(np.array([1, 2, 3, 4, 5]), 2) -> [1.5, 2.5, 3.5, 4.5]
Solve “Rolling Mean Without a Loop — cumsum or np.convolve” in your browser →

13. Solve a System of Equations — np.linalg.solve

Medium2 ways to solve
📤 OUTPUT: return a NumPy array, e.g. [10.0, 30.0]. Use `return`, not print().
Real world: 2 pens + 3 books = 110,  1 pen + 1 book = 40.  Price of each?
    solve_prices([[2, 3], [1, 1]], [110, 40]) -> [10.0, 30.0]   (rounded to 2)
Solve “Solve a System of Equations — np.linalg.solve” in your browser →

14. Store x Month Sales Dashboard

Medium1 way to solve
📤 OUTPUT: return a dict, e.g. {'best_store': 1, 'best_month': 0, 'growth': […. Use `return`, not print().
sales: 2-D array (rows = stores, columns = months).
Return a dict: {"best_store": index of the store with the highest total,
                "best_month": index of the month with the highest total,
                "growth": list, per store, of (last month - first month)}  (Python ints)
    sales_insights(np.array([[10, 20, 30], [40, 10, 20]]))
    -> {"best_store": 1, "best_month": 0, "growth": [20, -20]}
Solve “Store x Month Sales Dashboard” in your browser →

15. Count Each Category — np.unique(return_counts=True)

Easy2 ways to solve
📤 OUTPUT: return a dict, e.g. {1: 1, 2: 1, 3: 3}. Use `return`, not print().
Return a dict {value: count} with Python ints.
    unique_counts(np.array([3, 1, 3, 3, 2])) -> {1: 1, 2: 1, 3: 3}
Solve “Count Each Category — np.unique(return_counts=True)” in your browser →

16. Photo Filter — interview at a photo-sharing app

Project1 way to solve
📤 OUTPUT: return a NumPy uint8 array, same shape as img. Use `return`, not print().
Interviewer: "Implement the brightness/contrast slider. It must be fast: no Python loops over pixels."
img: 2-D uint8 array (0..255).  out = (img - 128) * contrast + 128 + brightness,
rounded with np.rint, clipped to 0..255, returned as dtype uint8.
Trap: doing maths directly on uint8 wraps around (250 + 10 = 4!). Convert to float first.
Solve “Photo Filter — interview at a photo-sharing app” in your browser →

17. Stage 15 — Vectorised Execution (compile ONCE, run on 1,000,000 inputs: how JITs/NumPy win)

Compiler1 way to solve
📤 OUTPUT: return a NumPy array, e.g. array([1, 2, 5]). Use `return`, not print().
rpn: list of strings where "x" means the NumPy array x, other tokens are numbers, operators + - * / **.
Evaluate with a stack (looping over TOKENS is fine; never loop over x's elements).
If the result is a plain number, broadcast it to x's shape. Return a NumPy array.
    vectorized_eval(["x", "2", "**", "1", "+"], np.array([0, 1, 2])) -> array([1, 2, 5])
Solve “Stage 15 — Vectorised Execution (compile ONCE, run on 1,000,000 inputs: how JITs/NumPy win)” in your browser →

← CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests) PANDAS (DataFrames & structured data manipulation) →