Bird
0
0

Identify the error in this SciPy code snippet:

medium📝 Debug Q6 of 15
SciPy - Advanced Optimization
Identify the error in this SciPy code snippet:
from scipy.optimize import minimize

result = minimize(lambda x: sum(x**2), 5)
print(result.x)
AThe lambda function should not use sum()
BThe initial guess should be an array, not a scalar
Cminimize cannot optimize functions with powers
Dprint statement syntax is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Check the function input

    The function expects x to be an array because sum(x**2) sums over elements.
  2. Step 2: Initial guess type

    The initial guess provided is a scalar (5), which causes a shape mismatch.
  3. Step 3: Correct usage

    Initial guess should be an array, e.g., [5] or [5, 5].
  4. Final Answer:

    The initial guess should be an array, not a scalar -> Option B
  5. Quick Check:

    Initial guess shape must match function input [OK]
Quick Trick: Initial guess must match input shape [OK]
Common Mistakes:
  • Passing scalar instead of array for vector functions
  • Misusing sum() in lambda without array input
  • Assuming minimize can't handle powers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes