B. Error: 10.sum() is invalid; fix by using (arr < 10).sum()
C. No error; output is boolean array
D. Error: arr < 10 is invalid; fix by using arr.sum() < 10
Solution
Step 1: Identify the error in expression
10.sum() is invalid because 10 is an integer, not an array.
Step 2: Correct the syntax to sum boolean array
Use parentheses to sum the boolean array: (arr < 10).sum().
Final Answer:
Error: 10.sum() is invalid; fix by using (arr < 10).sum() -> Option B
Quick Check:
Parentheses needed before sum() [OK]
Hint: Always put parentheses around condition before sum() [OK]
Common Mistakes:
Calling sum() on number instead of boolean array
Confusing comparison and sum order
Ignoring error message details
5. Given a 2D NumPy array data = np.array([[3, 7, 2], [5, 1, 8], [6, 4, 9]]), how can you count how many elements are greater than 5 across the entire array?
hard
A. (data > 5).sum()
B. data[data > 5].count()
C. data.sum() > 5
D. np.count(data > 5)
Solution
Step 1: Create boolean array for elements > 5
data > 5 creates a boolean array marking elements greater than 5.
Step 2: Sum True values to count elements
Use (data > 5).sum() to count all True values in the 2D array.
Final Answer:
(data > 5).sum() -> Option A
Quick Check:
Sum boolean mask counts elements > 5 [OK]
Hint: Sum boolean mask over entire array to count matches [OK]