Filter a NumPy array to elements greater than 10 and even with one boolean mask
Quick Overview
Return the elements of a 1-D NumPy array that are greater than 10 and even by combining two conditions into one boolean mask. It tests element-wise logical operators, Python operator precedence with comparisons, and how boolean indexing behaves.
Filter a NumPy array to elements greater than 10 and even with one boolean mask
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array `arr`, return a new array of the elements that are both greater than 10 and even. Build a single boolean mask combining both conditions with `&`, then index `arr`.
Requirements:
- Combine `arr > 10` and `arr % 2 == 0` with `&`, each wrapped in parentheses (operator precedence).
- Return a 1-D array, preserving order.
For example:
```text
Input: arr = np.array([4, 12, 15, 20, 11, 30])
Output: array([12, 20, 30])
```
4 is even but not greater than 10, and 15 and 11 are greater than 10 but odd, so only 12, 20 and 30 pass both conditions.
```hint Check what each piece evaluates to
Each condition should produce a boolean array the same length as `arr`. Work out what Python evaluates first if you leave the parentheses out.
```
### Constraints & Assumptions
- `arr` is a 1-D NumPy array of integers.
- The result keeps the original order of the selected elements and may be empty.
### What a Strong Answer Covers
- Building one element-wise boolean mask from both conditions and indexing with it.
- Why `&` is needed in place of Python's `and`.
- Why each comparison needs its own parentheses, with the actual parse of the unparenthesized expression.
- The cost of the approach and what happens when nothing matches.
### Follow-up Questions
- Why must each condition be wrapped in parentheses with `&`?
- Why use `&` instead of Python's `and`?
- How would you return the positions of the matching elements instead of their values?
Overview: Return the elements of a 1-D NumPy array that are greater than 10 and even by combining two conditions into one boolean mask. It tests element-wise logical operators, Python operator precedence with comparisons, and how boolean indexing behaves.
Given a 1-D NumPy array arr, return a new array of the elements that are both greater than 10 and even. Build a single boolean mask combining both conditions with &, then index arr.
Requirements:
Combine
arr > 10
and
arr % 2 == 0
with
&
, each wrapped in parentheses (operator precedence).