Bird
Raised Fist0
SciPydata~20 mins

Constrained optimization in SciPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Constrained Optimization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of constrained minimization with inequality
What is the minimum value found by this constrained optimization code using scipy.optimize.minimize?
SciPy
from scipy.optimize import minimize

# Objective function
f = lambda x: (x[0]-1)**2 + (x[1]-2.5)**2

# Constraint: x0 + x1 >= 2
cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] - 2})

# Initial guess
x0 = [2, 0]

res = minimize(f, x0, constraints=cons)
print(round(res.fun, 4))
A0.25
B0.0
C1.25
D2.25
Attempts:
2 left
💡 Hint
Think about the point closest to (1, 2.5) that satisfies x0 + x1 >= 2.
❓ data_output
intermediate
2:00remaining
Number of iterations in constrained optimization
How many iterations does the following constrained optimization take to converge?
SciPy
from scipy.optimize import minimize

f = lambda x: (x[0]-3)**2 + (x[1]+1)**2
cons = ({'type': 'eq', 'fun': lambda x: x[0] - 2*x[1]})
x0 = [0, 0]
res = minimize(f, x0, constraints=cons)
print(res.nit)
A7
B3
C10
D5
Attempts:
2 left
💡 Hint
Check the number of iterations attribute in the result object.
🔧 Debug
advanced
2:00remaining
Identify the error in constraint definition
What error will this code raise when running scipy.optimize.minimize with the given constraints?
SciPy
from scipy.optimize import minimize

f = lambda x: x[0]**2 + x[1]**2
cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 1},
        {'type': 'eq', 'fun': lambda x: x[1] + 2})
x0 = [0, 0]
res = minimize(f, x0, constraints=cons)
print(res.fun)
ATypeError: 'tuple' object is not callable
BValueError: Constraints must be a dict or list of dicts
CRuntimeWarning: Initial guess does not satisfy constraints
DNo error, outputs 1.0
Attempts:
2 left
💡 Hint
Check if the initial guess satisfies the constraints.
❓ visualization
advanced
3:00remaining
Plot of feasible region and minimum point
Which plot correctly shows the feasible region and the minimum point for the problem: Minimize f(x,y) = (x-2)^2 + (y-3)^2 Subject to constraints: x + y <= 4 and x >= 0, y >= 0?
SciPy
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1,5,400)
y = np.linspace(-1,5,400)
X, Y = np.meshgrid(x,y)
Z = (X-2)**2 + (Y-3)**2

plt.contour(X, Y, Z, levels=30)
plt.fill_between(x, 0, 4 - x, where=(x<=4), color='lightblue', alpha=0.5)
plt.xlim(-1,5)
plt.ylim(-1,5)
plt.scatter(1.5, 2.5, color='red', label='Minimum')
plt.legend()
plt.show()
APlot with shaded square region from (0,0) to (4,4) with red dot at (2,3)
BPlot with shaded triangle region bounded by x=0, y=0, and x+y=4 with red dot at (1.5, 2.5)
CPlot with shaded circle region centered at (2,3) with red dot at (2,3)
DPlot with no shading and red dot at (0,0)
Attempts:
2 left
💡 Hint
The feasible region is where x and y are non-negative and their sum is at most 4.
🚀 Application
expert
3:00remaining
Interpreting Lagrange multipliers from constrained optimization
After solving the constrained optimization problem: Minimize f(x,y) = x^2 + y^2 Subject to x + 2y = 6 The solver returns Lagrange multiplier value 3. What does this multiplier represent?
AThe rate of increase in the minimum value of f when the constraint constant increases by 1
BThe minimum value of the function f at the solution point
CThe value of x at the solution point
DThe number of iterations the solver took
Attempts:
2 left
💡 Hint
Lagrange multipliers measure sensitivity of the optimal value to constraint changes.

Practice

(1/5)
1. What is the main purpose of constrained optimization in scipy.optimize.minimize?
easy
A. To only check if constraints are valid
B. To find any random solution without restrictions
C. To find the best solution while respecting given limits or rules
D. To maximize the function without any constraints

Solution

  1. Step 1: Understand constrained optimization goal

    Constrained optimization aims to find the best (minimum or maximum) value of a function while following certain limits or rules called constraints.
  2. Step 2: Relate to scipy.optimize.minimize usage

    The minimize function in scipy can include constraints and bounds to ensure the solution respects these limits.
  3. Final Answer:

    To find the best solution while respecting given limits or rules -> Option C
  4. Quick Check:

    Constrained optimization = best solution within limits [OK]
Hint: Constrained means limits must be followed [OK]
Common Mistakes:
  • Thinking constraints are optional or ignored
  • Confusing constrained with unconstrained optimization
  • Assuming constraints only check validity, not guide solution
2. Which of the following is the correct way to define the inequality constraint `x[0] >= 1` for scipy.optimize.minimize?
easy
A. constraint = {'type': 'eq', 'fun': lambda x: x[0] - 1}
B. constraint = {'type': 'ineq', 'fun': lambda x: x[0] - 1}
C. constraint = {'type': 'ineq', 'fun': lambda x: 1 - x[0]}
D. constraint = {'type': 'eq', 'fun': lambda x: 1 - x[0]}

Solution

  1. Step 1: Recall inequality constraint definition

    Inequality constraints require the function to be >= 0. So, fun(x) >= 0 means the constraint holds.
  2. Step 2: Check each option

    constraint = {'type': 'ineq', 'fun': lambda x: x[0] - 1}: lambda x: x[0] - 1 means x[0] - 1 >= 0 or x[0] >= 1, correct for the constraint.
    Options B and D use 'eq' which means equality, not inequality.
    constraint = {'type': 'ineq', 'fun': lambda x: 1 - x[0]} means 1 - x[0] >= 0 or x[0] <= 1, which is a different constraint.
  3. Final Answer:

    constraint = {'type': 'ineq', 'fun': lambda x: x[0] - 1} -> Option B
  4. Quick Check:

    Inequality means fun(x) >= 0 [OK]
Hint: Inequality means function output ≥ 0 [OK]
Common Mistakes:
  • Using 'eq' instead of 'ineq' for inequalities
  • Reversing the inequality sign in the function
  • Confusing the function output sign for constraints
3. What will be the output of this code snippet?
from scipy.optimize import minimize

fun = lambda x: (x[0]-2)**2 + (x[1]-3)**2
cons = ({'type': 'eq', 'fun': lambda x: x[0] + x[1] - 5})
res = minimize(fun, [0, 0], constraints=cons)
print(res.x.round(2))
medium
A. [2.5 2.5]
B. [1.0 4.0]
C. [0.0 5.0]
D. [2.0 3.0]

Solution

  1. Step 1: Understand the objective and constraint

    The function minimizes distance from point (2,3). The constraint requires x[0] + x[1] = 5.
  2. Step 2: Find point on line x0+x1=5 closest to (2,3)

    We want to minimize (x0-2)^2 + (x1-3)^2 with x0+x1=5. Using substitution: x1=5-x0.
    Objective becomes (x0-2)^2 + (5-x0-3)^2 = (x0-2)^2 + (2 - x0)^2.
    Expanding: (x0-2)^2 + (2-x0)^2 = 2*(x0-2)^2.
    Minimum at x0=2, then x1=3, which satisfies the constraint.
  3. Step 3: Check options

    [2.0 3.0] matches the minimum (2.0, 3.0). [1.0 4.0] sums to 5 but is farther from (2,3). The solver converges to [2.0, 3.0].
  4. Final Answer:

    [2.0 3.0] -> Option D
  5. Quick Check:

    Minimum at (2,3) on constraint line [OK]
Hint: Check constraint line and closest point to target [OK]
Common Mistakes:
  • Ignoring the constraint when finding minimum
  • Confusing initial guess with solution
  • Assuming solver returns initial guess
4. Identify the error in this constrained optimization code:
from scipy.optimize import minimize

fun = lambda x: x[0]**2 + x[1]**2
cons = [{'type': 'ineq', 'fun': lambda x: x[0] + x[1] - 1}]
res = minimize(fun, [0, 0], constraints=cons)
print(res.x)
medium
A. Initial guess violates the inequality constraint
B. Constraint function should return negative values
C. Constraints must be a dictionary, not a list
D. Objective function must be linear

Solution

  1. Step 1: Check initial guess against constraint

    The inequality constraint requires x[0] + x[1] - 1 >= 0, or x[0] + x[1] >= 1.
    The initial guess is [0,0], sum is 0, which violates the constraint.
  2. Step 2: Understand impact of violating initial guess

    Starting from a point that violates constraints can cause solver to fail or give warnings.
    Other options are incorrect because:
    - Constraint function should return >=0 for valid points.
    - Constraints can be a list of dicts.
    - Objective function can be nonlinear.
  3. Final Answer:

    Initial guess violates the inequality constraint -> Option A
  4. Quick Check:

    Initial guess must satisfy constraints [OK]
Hint: Check if initial guess meets constraints [OK]
Common Mistakes:
  • Ignoring initial guess validity
  • Misunderstanding constraint function sign
  • Thinking constraints must be single dict
5. You want to minimize f(x) = (x[0]-1)^2 + (x[1]-2)^2 with constraints x[0] >= 0, x[1] >= 0, and x[0] + 2*x[1] = 3. Which setup correctly applies these constraints using scipy.optimize.minimize?
hard
A. bounds = [(0, None), (0, None)]; cons = {'type': 'eq', 'fun': lambda x: x[0] + 2*x[1] - 3}
B. bounds = [(None, 0), (None, 0)]; cons = {'type': 'ineq', 'fun': lambda x: 3 - x[0] - 2*x[1]}
C. bounds = [(0, None), (0, None)]; cons = {'type': 'ineq', 'fun': lambda x: x[0] + 2*x[1] - 3}
D. bounds = [(0, None), (0, None)]; cons = {'type': 'ineq', 'fun': lambda x: 3 - x[0] - 2*x[1]}

Solution

  1. Step 1: Set bounds for inequalities

    Constraints x[0] >= 0 and x[1] >= 0 are bounds: [(0, None), (0, None)] means lower bound 0, no upper bound.
  2. Step 2: Define equality constraint

    The equality x[0] + 2*x[1] = 3 is expressed as fun(x) = x[0] + 2*x[1] - 3 = 0 with type 'eq'.
  3. Step 3: Check options

    bounds = [(0, None), (0, None)]; cons = {'type': 'eq', 'fun': lambda x: x[0] + 2*x[1] - 3} correctly sets bounds and equality constraint.
    bounds = [(None, 0), (None, 0)]; cons = {'type': 'ineq', 'fun': lambda x: 3 - x[0] - 2*x[1]} reverses bounds and uses inequality instead of equality.
    bounds = [(0, None), (0, None)]; cons = {'type': 'ineq', 'fun': lambda x: x[0] + 2*x[1] - 3} uses inequality for equality constraint.
    bounds = [(0, None), (0, None)]; cons = {'type': 'ineq', 'fun': lambda x: 3 - x[0] - 2*x[1]} uses inequality (x[0] + 2*x[1] <= 3) instead of equality.
  4. Final Answer:

    bounds = [(0, None), (0, None)]; cons = {'type': 'eq', 'fun': lambda x: x[0] + 2*x[1] - 3} -> Option A
  5. Quick Check:

    Bounds for inequalities + 'eq' for equality [OK]
Hint: Use bounds for ≥ constraints, 'eq' for equalities [OK]
Common Mistakes:
  • Using 'ineq' for equality constraints
  • Reversing bounds limits
  • Confusing constraint function sign
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard