0
0
SciPydata~10 mins

Bounds and constraints in SciPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define bounds for the variables in the optimization problem.

SciPy
from scipy.optimize import minimize

bounds = [[1]]

result = minimize(lambda x: x[0]**2 + x[1]**2, [1, 1], bounds=bounds)
print(result.x)
Drag options to blanks, or click blank then click option'
A(0, None), (0, None)
B[0, None], [0, None]
C[(0, None), (0, None)]
D0, None, 0, None
Attempts:
3 left
💡 Hint
Common Mistakes
Using a tuple instead of a list for bounds
Not enclosing bounds in a list
Using separate tuples without a list
2fill in blank
medium

Complete the code to define a linear constraint for the optimization problem.

SciPy
from scipy.optimize import LinearConstraint

constraint = LinearConstraint([1], 0, 10)

print(constraint)
Drag options to blanks, or click blank then click option'
A[1, 2]
B[1, 2, 3]
C[[1], [2]]
D[[1, 2]]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a 1D list instead of 2D list
Using incorrect dimensions for the constraint matrix
3fill in blank
hard

Fix the error in the code by completing the constraint definition correctly.

SciPy
from scipy.optimize import minimize, LinearConstraint
import numpy as np

A = np.array([[1, 2], [3, 4]])
constraint = LinearConstraint(A, [1], [10, 20])

result = minimize(lambda x: x[0]**2 + x[1]**2, [1, 1], constraints=[constraint])
print(result.x)
Drag options to blanks, or click blank then click option'
A[0, 0]
B[5, 15]
C[10, 20]
D[1, 2]
Attempts:
3 left
💡 Hint
Common Mistakes
Setting lower bounds higher than upper bounds
Using incorrect array sizes for bounds
4fill in blank
hard

Fill both blanks to create a nonlinear constraint function and define it properly.

SciPy
from scipy.optimize import minimize, NonlinearConstraint
import numpy as np

def constraint_func(x):
    return x[0]**2 + x[1]**2 - [1]

nlc = NonlinearConstraint(constraint_func, 0, [2])

result = minimize(lambda x: x[0] + x[1], [1, 1], constraints=[nlc])
print(result.x)
Drag options to blanks, or click blank then click option'
A1
B2
C3
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using bounds that do not match the function output range
Confusing the constant subtracted in the function
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that filters variables based on bounds.

SciPy
variables = {'x': 5, 'y': 10, 'z': 15}
bounds = {'x': (0, 10), 'y': (5, 15), 'z': (10, 20)}
filtered = [1]: variables[[2]] for [3] in variables if bounds[[3]][0] <= variables[[3]] <= bounds[[3]][1]}
print(filtered)
Drag options to blanks, or click blank then click option'
Ak
Bv
Dkey
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently
Using values instead of keys in the comprehension