NumPy Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints placeholder results, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Try for a few minutes before you open the solution. Try to solve every exercise without a Python loop.
| # | Exercise | Topics |
|---|---|---|
| 1 | Grid basics | arange, reshape, slicing |
| 2 | Checkerboard | step slicing, assignment |
| 3 | Sensor filter | boolean masks, np.where |
| 4 | Min-max scaling | aggregations along an axis, broadcasting |
| 5 | Two dice | random Generator, bincount |
| 6 | Warmer days | np.diff, argmax |
| 7 | Report card | mean(axis=1), np.select |
| 8 | Three equations | np.linalg.solve |
| 9 | Fill the gaps | NaN, nanmean, np.where |
| 10 | Leaderboard | argsort, lexsort |
1. Grid basics
Create the numbers 1 to 12 as a 3×4 array. Print the array, its last column, and the 2×2 block made of rows 1–2 and columns 1–2.
Expected: last column [ 4 8 12], block [[ 6 7] [10 11]].
import numpy as np
grid = np.zeros((3, 4), dtype=int) # TODO: build 1..12 as a 3x4 array
print(grid)
print(grid[0]) # TODO: last column
print(grid[:1, :1]) # TODO: the 2x2 block[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
[0 0 0 0]
[[0]]
Show solution
import numpy as np
grid = np.arange(1, 13).reshape(3, 4)
print(grid)
print(grid[:, -1])
print(grid[1:, 1:3])2. Checkerboard
Build a 6×6 integer checkerboard of 0s and 1s whose top-left cell is 0, then print it and the number of 1s. Hint: two step-slice assignments are enough.
Expected first two rows: [0 1 0 1 0 1] and [1 0 1 0 1 0]; number of ones: 18.
import numpy as np
board = np.zeros((6, 6), dtype=int)
# TODO: set the "black" squares to 1
print(board)
print(board.sum())[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
0
Show solution
import numpy as np
board = np.zeros((6, 6), dtype=int)
board[::2, 1::2] = 1 # even rows, odd columns
board[1::2, ::2] = 1 # odd rows, even columns
print(board)
print(board.sum())3. Sensor filter
From the readings below, print (a) only the values between 10 and 20 inclusive, and (b) a copy where every value above 20 is capped at 20.
Expected: [18 11 20 14 10] and [ 4 18 20 11 9 20 14 20 10].
import numpy as np
readings = np.array([4, 18, 25, 11, 9, 20, 14, 30, 10])
in_range = readings # TODO: boolean mask
capped = readings # TODO: np.where (or np.minimum)
print(in_range)
print(capped)[ 4 18 25 11 9 20 14 30 10]
[ 4 18 25 11 9 20 14 30 10]
Show solution
import numpy as np
readings = np.array([4, 18, 25, 11, 9, 20, 14, 30, 10])
print(readings[(readings >= 10) & (readings <= 20)])
print(np.where(readings > 20, 20, readings)) # or np.minimum(readings, 20)4. Min-max scaling
Scale each column of X to the range 0–1 with (x − min) / (max − min), using the column's own min and max. Print the result rounded to 3 decimals.
Expected:
[[0. 0.333]
[0.333 1. ]
[0.667 0.667]
[1. 0. ]]import numpy as np
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 300.0],
[4.0, 100.0]])
scaled = X * 0 # TODO
print(scaled.round(3))[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
Show solution
import numpy as np
X = np.array([[1.0, 200.0], [2.0, 400.0], [3.0, 300.0], [4.0, 100.0]])
lo = X.min(axis=0) # shape (2,): one value per column
hi = X.max(axis=0)
scaled = (X - lo) / (hi - lo) # broadcasting over the rows
print(scaled.round(3))5. Two dice
Using rng = np.random.default_rng(2024), roll two dice 10,000 times with one call (size=(10_000, 2)). Print the estimated probability that the total is 7 (4 decimals) and the most common total.
Expected: P(sum = 7) ~ 0.1667 and most common sum: 7. (Theory: 6/36 ≈ 0.1667.)
import numpy as np
rng = np.random.default_rng(2024)
totals = np.array([2, 7, 12]) # TODO: roll and sum each row
print(f"P(sum = 7) ~ {np.mean(totals == 7):.4f}")
print("most common sum:", 0) # TODO: np.bincount(...).argmax()P(sum = 7) ~ 0.3333
most common sum: 0
Show solution
import numpy as np
rng = np.random.default_rng(2024)
rolls = rng.integers(1, 7, size=(10_000, 2))
totals = rolls.sum(axis=1)
print(f"P(sum = 7) ~ {np.mean(totals == 7):.4f}")
print("most common sum:", np.bincount(totals).argmax())6. Warmer days
For the daily temperatures below, print the day-to-day changes, how many days were warmer than the day before, and the biggest rise with the two day indices it happened between.
Expected: rises: [ 2 -1 3 3 -2 3 2 -1], warmer days: 5, biggest rise: 3 between day 2 and 3.
import numpy as np
temps = np.array([14, 16, 15, 18, 21, 19, 22, 24, 23])
rise = temps[:1] # TODO: np.diff
print("rises:", rise)
print("warmer days:", 0) # TODO
print("biggest rise:", rise.max(), "between day", 0, "and", 1) # TODOrises: [14]
warmer days: 0
biggest rise: 14 between day 0 and 1
Show solution
import numpy as np
temps = np.array([14, 16, 15, 18, 21, 19, 22, 24, 23])
rise = np.diff(temps)
print("rises:", rise)
print("warmer days:", (rise > 0).sum())
i = rise.argmax() # first position of the largest rise
print("biggest rise:", rise.max(), "between day", i, "and", i + 1)7. Report card
Each row holds one student's two exam scores. Compute each student's average and turn it into a letter: A for ≥ 85, B for ≥ 70, C for ≥ 50, otherwise F.
Expected: [86.5 56. 67.5 93.5] ['A' 'C' 'C' 'A'].
import numpy as np
scores = np.array([[82, 91],
[45, 67],
[77, 58],
[99, 88]])
avg = scores[:, 0] * 1.0 # TODO: row averages
grades = np.full(len(avg), "?") # TODO: np.select
print(avg, grades)[82. 45. 77. 99.] ['?' '?' '?' '?']
Show solution
import numpy as np
scores = np.array([[82, 91], [45, 67], [77, 58], [99, 88]])
avg = scores.mean(axis=1)
grades = np.select([avg >= 85, avg >= 70, avg >= 50], ["A", "B", "C"], default="F")
print(avg, grades)8. Three equations
Solve the system and print [x y z]:
x + y + z = 6
2y + 5z = -4
2x + 5y - z = 27Expected: [ 5. 3. -2.].
import numpy as np
A = np.array([[1.0, 1.0, 1.0],
[0.0, 2.0, 5.0],
[2.0, 5.0, -1.0]])
b = np.array([6.0, -4.0, 27.0])
solution = np.zeros(3) # TODO: use np.linalg
print(solution)[0. 0. 0.]
Show solution
import numpy as np
A = np.array([[1.0, 1.0, 1.0], [0.0, 2.0, 5.0], [2.0, 5.0, -1.0]])
b = np.array([6.0, -4.0, 27.0])
print(np.linalg.solve(A, b))9. Fill the gaps
Replace every NaN in data with the mean of its column (ignoring NaNs). Print the column means and the filled table.
Expected column means [5. 8. 8.] and filled table:
[[ 1. 8. 3.]
[ 4. 5. 8.]
[ 5. 8. 9.]
[10. 11. 12.]]import numpy as np
data = np.array([[1.0, np.nan, 3.0],
[4.0, 5.0, np.nan],
[np.nan, 8.0, 9.0],
[10.0, 11.0, 12.0]])
col_means = np.zeros(3) # TODO
filled = data # TODO
print(col_means)
print(filled)[0. 0. 0.]
[[ 1. nan 3.]
[ 4. 5. nan]
[nan 8. 9.]
[10. 11. 12.]]
Show solution
import numpy as np
data = np.array([[1.0, np.nan, 3.0], [4.0, 5.0, np.nan],
[np.nan, 8.0, 9.0], [10.0, 11.0, 12.0]])
col_means = np.nanmean(data, axis=0)
filled = np.where(np.isnan(data), col_means, data) # col_means broadcasts over rows
print(col_means)
print(filled)10. Leaderboard
Print the top 3 players by points, highest first. Ties must be broken alphabetically by name.
Expected: ['Bo' 'Dev' 'Eli'] [515 515 480].
import numpy as np
names = np.array(["Ana", "Bo", "Cleo", "Dev", "Eli", "Fin"])
points = np.array([340, 515, 290, 515, 480, 120])
order = np.arange(3) # TODO: indices of the top 3
print(names[order], points[order])['Ana' 'Bo' 'Cleo'] [340 515 290]
Show solution
import numpy as np
names = np.array(["Ana", "Bo", "Cleo", "Dev", "Eli", "Fin"])
points = np.array([340, 515, 290, 515, 480, 120])
# lexsort: the LAST key is the primary one. -points sorts high to low,
# names breaks ties alphabetically.
order = np.lexsort((names, -points))[:3]
print(names[order], points[order])A plain np.argsort(points)[::-1][:3] gets the scores right but lists Dev before Bo, because reversing an ascending sort also reverses the order of tied names.
Test yourself
In Exercise 4, why does X - X.min(axis=0) work without a loop?
- NumPy converts X to a list
- The (2,) array of column minimums broadcasts over every row of the (4, 2) array
- min returns a scalar
- It only works for square arrays
Which expression counts the elements of a greater than 5?
- a[a > 5]
- (a > 5).sum()
- np.where(a > 5)
- a.count(5)
In np.lexsort((names, -points)), which key decides the order first?
- names
- -points
- Both equally
- The index