Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Practice and Review

Exercises with Solutions

Twelve SciPy practice problems on optimization, integration, ODEs, statistics, signals and sparse matrices. Each one has a runnable, checked solution.

Reading about SciPy teaches you the vocabulary. Writing code teaches you the language. This lesson gives you twelve exercises spread across the library: optimization, integration, differential equations, statistics, signal processing, sparse matrices and graphs. Each exercise states a small, concrete problem. Try it on your own first in a scratch cell; then open the solution, which is a live editor you can change and rerun.

Do not be discouraged when something fails. Reading an error message, checking res.success and printing the shape of an array are the real skills. If you get stuck, the matching lesson is linked in the hint.

flowchart LR
    A["Read the problem"] --> B["Sketch the inputs<br/>and expected output"]
    B --> C["Try it yourself"]
    C --> D{"Result matches<br/>a check you trust?"}
    D -->|"no"| E["Print shapes, residuals,<br/>res.message"]
    E --> C
    D -->|"yes"| F["Compare with the solution"]

A good practice loop: always have a check that does not depend on the code being right, such as a known answer or a residual.

Part 1: Optimization

Exercise 1: Minimize with constraints

Minimize f(x, y) = (x - 1)^2 + (y - 2.5)^2 subject to x >= 0, y >= 0 and the three linear constraints x - 2y + 2 >= 0, -x - 2y + 6 >= 0 and -x + 2y + 2 >= 0. Start from (2, 0) and report the solution and the minimum value.

Hint: Constraints, Bounds and Global Optimization. Constraints of type "ineq" mean fun(x) >= 0.

Python Solution 1: SLSQP with constraints

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.

The unconstrained minimum (1, 2.5) violates the first constraint, so the answer sits on that constraint's boundary, at (1.4, 1.7) with value 0.8.

Exercise 2: Fit a decay with an offset

Generate data y = 5 * exp(-0.4 t) + 1 plus Gaussian noise (standard deviation 0.05) for 60 points t in [0, 10], using default_rng(1). Fit a * exp(-k t) + c with curve_fit and print the parameters with their standard errors.

Hint: Curve Fitting and Least Squares. Standard errors are the square roots of the diagonal of the covariance matrix.

Python Solution 2: curve_fit with errors

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.

The estimates land within about one standard error of the true values 5, 0.4 and 1.

Exercise 3: Production planning with linprog

A workshop makes tables (profit 40 each) and chairs (profit 30 each). Resource 1 allows 2 tables + 1 chair <= 100, resource 2 allows 1 table + 1 chair <= 80, and resource 3 allows 1 table + 2 chairs <= 90. Maximize the profit and say which resource is not a bottleneck.

Hint: Linear and Integer Programming. linprog minimizes, so negate the objective. With the HiGHS methods, res.ineqlin.marginals holds the dual values.

Python Solution 3: linear program with duals

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.

Resource 2 has 80 - (36.67 + 26.67) = 16.67 units left over and a shadow price of 0, so it is not a bottleneck. Extra units of resources 1 and 3 would raise the profit by 16.67 and 6.67 per unit.

Part 2: Integration and differential equations

Exercise 4: Two integrals

Compute (a) the integral of x * exp(-x) from 0 to infinity, which equals 1, and (b) the area of the unit disc using dblquad, which equals pi.

Hint: Numerical Integration. dblquad(func, a, b, gfun, hfun) integrates func(y, x) with y as the inner variable.

Python Solution 4: quad and dblquad

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: When does the population reach half of capacity?

A logistic population obeys dy/dt = r * y * (1 - y / K) with r = 0.5, K = 100 and y(0) = 5. Use solve_ivp with an event to find the time when y first reaches 50, and compare it with the closed form ln(K / y0 - 1) / r.

Hint: Solving ODEs with solve_ivp. An event function returns zero at the moment of interest; set terminal = True to stop there.

Python Solution 5: ODE event detection

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 6: Fixed point of cosine

Find the number x with cos(x) = x and report how small the residual is.

Hint: Scalar Minimization and Root Finding. Turn it into a root problem for cos(x) - x and bracket the root between 0 and 1.

Python Solution 6: brentq

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: Statistics

Exercise 7: Compare two groups

Draw 40 values from a normal distribution with mean 50 (group 1) and 40 values with mean 56 (group 2), both with standard deviation 10, using default_rng(3). Run Welch's t-test, report the 95 percent confidence interval for the mean difference and compute Cohen's d.

Hint: Hypothesis Testing. Use equal_var=False, and note that the p-value alone does not tell you how large the effect is.

Python Solution 7: Welch test and effect size

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.

The interval is wide and only just excludes zero. The p-value is close to 0.05, and Cohen's d of about 0.45 is a small-to-medium effect. With 40 per group, the test is only borderline powered for a 6-point shift.

Exercise 8: Bootstrap the median

Generate 80 log-normal values (default_rng(4), lognormal(3, 0.5, 80)) and compute a 95 percent bootstrap interval for the median.

Hint: Correlation, Regression and Bootstrap. Pass the data as a tuple, (data,).

Python Solution 8: bootstrap of a median

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: Signals

Exercise 9: Remove a 50 Hz hum

A 5 Hz sine wave sampled at 500 Hz for two seconds is polluted by a 50 Hz tone of amplitude 0.5. Design a 4th-order Butterworth low-pass filter with a 15 Hz cutoff, apply it with zero phase (sosfiltfilt), and compare the RMS error before and after.

Hint: Filter Design and Filtering Signals. With fs= given, the cutoff is in Hz. Use output="sos" for numerical stability.

Python Solution 9: Butterworth low-pass

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: Find the tones

A signal is sin(2 pi 12 t) + 0.5 sin(2 pi 31 t) sampled at 500 Hz for two seconds. Use the FFT to find which frequencies are present and their amplitudes.

Hint: The Fast Fourier Transform. Use rfft, rfftfreq, and find_peaks. To get an amplitude, divide the magnitude by N / 2.

Python Solution 10: spectrum peaks

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.

Both frequencies fall exactly on FFT bins because the signal lasts a whole number of periods, so the amplitudes come out as 1.00 and 0.50. With other frequencies you would see spectral leakage.

Part 5: Sparse matrices and graphs

Exercise 11: A million-entry system without a million-entry matrix

Build the 1000 by 1000 tridiagonal matrix with 2 on the diagonal and -1 beside it as a CSC sparse matrix, solve A x = 1 and verify the residual. Report the number of stored entries and the largest component of the solution.

Hint: Sparse Matrices and Sparse Linear Algebra and Graph Algorithms.

Python Solution 11: sparse tridiagonal solve

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.

The exact middle value is n (n + 1) / 8, about 125,250, so the answer is easy to verify.

Exercise 12: Shortest route

Six towns are connected by roads with these lengths: 0-1: 7, 0-2: 9, 0-5: 14, 1-2: 10, 1-3: 15, 2-3: 11, 2-5: 2, 3-4: 6, 4-5: 9. Find the shortest distances from town 0 and the route to town 4.

Hint: Sparse Linear Algebra and Graph Algorithms. dijkstra(..., return_predecessors=True) gives a predecessor array that you can follow backwards.

Python Solution 12: Dijkstra with a route

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.

The shortest way to town 4 is 0, 2, 5, 4 with total length 20. The tempting route 0, 2, 3, 4 costs 26 because the road 2-3 is long. If two routes tie, Dijkstra reports one of them, so enumerate paths yourself if you need all optimal routes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In SLSQP constraints of type 'ineq', which condition must the function value satisfy?

    SciPy's convention is that inequality constraints are satisfied when fun(x) >= 0. Remember to rewrite a '<=' condition by negating it.
  2. 2. linprog always minimizes. How do you maximize a profit with it?

    Maximizing f is the same as minimizing -f. Remember to flip the sign of the optimal value when you report it.
  3. 3. In an event function for solve_ivp, what does terminal = True do?

    A terminal event ends the integration where it occurs; direction restricts which crossings count.
  4. 4. Why is sosfiltfilt a good choice for cleaning up a recorded signal?

    Applying the filter in both directions cancels the phase delay, so features stay aligned with the original data. The cost is that it cannot run in real time.
  5. 5. A p-value of 0.049 and a 95% interval for the mean difference of [0.02, 9.8] together suggest what?

    The interval barely excludes zero and spans a huge range, so the data support a positive effect only weakly. Report the interval and the effect size, not just the p-value.

Summary

  • Constraints in SciPy follow conventions (ineq means >= 0; linprog minimizes), and half of solving a problem is translating it to those conventions.
  • Always compare a result to something independent: a closed form, a residual, a known shape.
  • Result objects (res.success, res.slack, res.ineqlin.marginals, sol.t_events) hold more information than the headline answer.
  • For statistics, report intervals and effect sizes alongside p-values, and fix random seeds.
  • Filtering and FFT exercises become easy to verify when you design the test signal yourself.
  • Sparse matrices and csgraph let ordinary-looking code handle problems whose dense versions would not fit in memory.

Next: test your conceptual understanding in Interview Questions.