Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 49 ยท Practice and Review

Practice Exercises

Practice NumPy with 20 graded exercises on array creation, indexing, broadcasting, aggregation and linear algebra. Every solution runs live in your browser.

Reading about NumPy teaches you the vocabulary; solving problems teaches you to think in arrays. This page has 20 exercises, ordered from easy to challenging, grouped by topic. Each one states a task, then gives a runnable solution in an editor. The solutions use assert statements, so a wrong edit of the code makes the run fail loudly, and they print what they computed so you can compare with your own answer.

How to use this page

For the best learning, do not run the solution first. Read the task, then write your own answer in a scratch editor (for example, delete the solution body in the editor below the task and type yours). Check your result against the printed output, and only then compare with the shown approach. If an exercise takes more than ten minutes, peek at the solution, then close it and redo it from memory the next day.

Three habits solve most array problems:

  1. Write down the shapes first. Before touching code, note the shape of every input and the shape you want.
  2. Prefer whole-array expressions over loops: slicing, masks, broadcasting, axis= aggregations.
  3. Check small cases by hand. Print a tiny example and make sure your expression does what you expect.
flowchart TD
    A["Read the task"] --> B["Write the input and<br/>output shapes"]
    B --> C{"Which tool fits?"}
    C -- "pick elements" --> D["Slicing, masks,<br/>fancy indexing"]
    C -- "combine arrays" --> E["Broadcasting,<br/>ufuncs, @"]
    C -- "summarize" --> F["Aggregations<br/>with axis"]
    D --> G["Print a small example<br/>and check by hand"]
    E --> G
    F --> G

A simple routine for attacking any array problem.

Part 1: Creating arrays

Related lessons: Your First Arrays and Creating Arrays.

Exercise 1. Create a 1D array containing the even numbers from 2 to 20 inclusive. Print it and its shape.

Python Exercise 1: even numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 2. Build an 8 by 8 checkerboard of zeros and ones, with a 0 in the top-left corner, without any loops.

Python Exercise 2: checkerboard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 3. Create 11 evenly spaced numbers from 0 to 1 (both ends included), then square them and round the result to 2 decimals.

Python Exercise 3: linspace and squares

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 4. Make a 4 by 4 matrix holding the numbers 1 to 16 in row order. Then extract its main diagonal, and build a new matrix that has that diagonal and zeros everywhere else.

Python Exercise 4: reshape and diagonal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 5. Using np.random.default_rng(42), draw 10 random integers from 0 to 99 inclusive. Print them with their dtype.

Python Exercise 5: seeded random integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 2: Indexing and selection

Related lessons: Indexing and Slicing, Boolean Masks and Fancy Indexing.

Exercise 6. Given a = np.arange(20), get (a) the last three elements, (b) every second element starting at index 1, (c) the whole array reversed.

Python Exercise 6: slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 7. Make g = np.arange(36).reshape(6, 6). Extract the 3 by 3 block in the middle (rows 2 to 4 and columns 2 to 4), the second column, and the last row.

Python Exercise 7: blocks, columns, rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 8. Among the integers 1 to 50, select those divisible by 3 but not divisible by 5. How many are there?

Python Exercise 8: combined mask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 9. Replace every negative number in [3, -1, 4, -1, -5, 9, -2, 6] with 0 without writing a loop. Do it two ways: with np.where and with np.clip.

Python Exercise 9: removing negatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 10. From m = np.arange(30).reshape(5, 6) select rows 0, 2 and 4 (all columns). Then use two index arrays to pick the single elements at positions (0, 1), (2, 3) and (4, 5).

Python Exercise 10: fancy indexing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 3: Broadcasting

Related lesson: Broadcasting.

Exercise 11. Print the 9 by 9 multiplication table (rows and columns labeled 1 to 9) with one multiplication and no loops.

Python Exercise 11: multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 12. Given a 4 by 3 matrix of numbers, subtract each column's mean from that column so every column has mean zero.

Python Exercise 12: centering columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 13. Scale every row of a matrix so that the row sums to 1. Watch out for the shape of the row sums.

Python Exercise 13: normalizing rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without keepdims=True the row sums have shape (3,), which would be matched against the columns and divide the wrong numbers (or fail). This is the most common axis mistake in practice.

Exercise 14. Five points lie in the plane. Compute the 5 by 5 table of distances between all pairs, then find the nearest neighbor of each point (not itself).

Python Exercise 14: pairwise distances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 4: Aggregation

Related lesson: Aggregations and Axes.

Exercise 15. Five students took four exams. Using one array of scores, find (a) each student's average, (b) which exam each student did best on (0-based), and (c) the class average per exam.

Python Exercise 15: scores table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 16. A savings account gets these monthly deposits: [30, 25, 40, 10, 55, 20, 45]. Compute the running balance, and find the first month (0-based) when the balance exceeds 100.

Python Exercise 16: running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If no value satisfied the condition, argmax would return 0, which looks like a valid answer. In real code, check with (balance > 100).any() first.

Exercise 17. Find the most frequent value (the mode) of [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] and how many times it occurs.

Python Exercise 17: the mode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 5: Linear algebra

Related lessons: Vectors and Dot Products, Matrix Operations and Solving Linear Systems.

Exercise 18. Solve the system 2x + y - z = 8, -3x - y + 2z = -11, -2x + y + 2z = -3, and verify that the solution satisfies the equations.

Python Exercise 18: solving a system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 19. For A = [[1, 2], [3, 4]] and B = [[0, 1], [1, 0]] compute A @ B, B @ A, and the elementwise product A * B. Are the first two equal? Also print the trace and determinant of A.

Python Exercise 19: matrix products

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 20. Points follow roughly y = 3x + 2 with a little noise. Using np.polyfit and, separately, np.linalg.lstsq, estimate the slope and intercept and check that the two methods agree.

Python Exercise 20: fitting a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 6: Polynomials, strings, math and statistics

Related lessons: Advanced Techniques, Vectorized Operations and ufuncs, Text and Dates, Statistics and Correlation and Bitwise Operations.

Exercise 21. Create the polynomial x^3 - 6x^2 + 11x - 6. Find its roots, evaluate it at x = 5, and compute its derivative. Check that every root really gives zero.

Python Exercise 21: polynomial roots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 22. Fit a quadratic to the points (0, 1), (1, 2), (2, 5), (3, 10), (4, 17), then predict the value at x = 6.

Python Exercise 22: fit and predict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 23. Given the array of names [" Ada ", "grace", "LINUS", "margaret hamilton"], produce a clean array with the whitespace removed and each word capitalised, and then an array with the length of every cleaned name.

Python Exercise 23: cleaning strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 24. Use np.arctan2 and np.hypot to convert the Cartesian points (1, 0), (0, 2), (-3, 0) and (1, 1) to polar form: a distance r and an angle in degrees between -180 and 180.

Python Exercise 24: Cartesian to polar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 25. Count how many days fall between 2024-02-20 and 2024-03-10, how many of them are business days, and which date is 10 business days after 2024-02-20.

Python Exercise 25: dates and business days

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 26. For the exam scores [55, 62, 71, 71, 78, 84, 90, 95, 95, 95] print the mean, median, standard deviation (population), the most common score, and the 25th and 75th percentiles.

Python Exercise 26: descriptive statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 27. Compute the Pearson correlation of hours = [1, 2, 3, 4, 5, 6] and marks = [52, 55, 61, 64, 72, 75], then standardise marks (z-scores) and check that the result has mean 0 and standard deviation 1.

Python Exercise 27: correlation and z-scores

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 28. The integers 1 to 20 are stored in an array. Using only bitwise operations, select the odd numbers and the numbers that are powers of two, and then use np.gcd.reduce to find the greatest common divisor of [84, 126, 210].

Python Exercise 28: bits and gcd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. You normalize the rows of a (3, 3) matrix with counts / counts.sum(axis=1) and the result looks wrong. What is the likely cause?

    A (3,) array lines up with the last axis, the columns. With keepdims=True the sums have shape (3, 1), so each row is divided by its own sum.
  2. 2. Which expression selects numbers that are divisible by 3 and not divisible by 5?

    Use the bitwise & operator on boolean arrays, with parentheses around each comparison. The plain 'and' raises an ambiguous truth value error, and && does not exist in Python.
  3. 3. What does m[[0, 2, 4], [1, 3, 5]] return?

    Two integer index arrays are paired element by element. To get the 3 by 3 block you would need np.ix_ or two steps.

Summary

  • Start every problem by writing down input and output shapes.
  • Creation: arange, linspace, indices, reshape, diag, and seeded default_rng.
  • Selection: slices are views, masks combine with &, | and ~, integer lists pair up.
  • Broadcasting combines a column (n, 1) with a row (1, m); keepdims=True keeps aggregation results broadcastable.
  • Aggregations take axis=; the axis you name is the one that disappears.
  • Linear algebra: solve instead of inv, @ for products, lstsq or polyfit for fits.

Keep going with the Interview Questions.