Clip Values to a Range Practice Problem
This data science coding problem helps you practice Array Manipulation, clip values to a range, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Manipulation.
- Problem ID: 58
- Problem key: 58-clip-values-to-a-range
- URL: https://datacrack.app/solve/58-clip-values-to-a-range
- Difficulty: easy
- Topic: Array Manipulation
- Module: NumPy Foundations
Problem Statement
# 🧩 Clip Values to a Range
---
### 🎯 Goal
**Clipping** caps values to a specified range — values below the minimum become the minimum, values above the maximum become the maximum. It's a standard data cleaning step for handling outliers without removing data points.
---
### 🔍 How Clipping Works
```
data: [-5, -2, 0, 3, 7, 12, 15]
clip(0, 10):
[ 0, 0, 0, 3, 7, 10, 10]
```
Values below 0 become 0, values above 10 become 10.
---
### 💻 Task
Implement `clip_array(data, min_val, max_val)` using `np.clip()`.
---
### 📥 Input
- `data`: list of numbers
- `min_val`: number — lower bound
- `max_val`: number — upper bound
### 📤 Output
- Clipped list of numbers
---
### 🧩 Starter Code
```python
import numpy as np
def clip_array(data, min_val, max_val):
"""
Clip values in an array to the range [min_val, max_val].
Args:
data (list): Input numbers
min_val (number): Minimum value (lower bound)
max_val (number): Maximum value (upper bound)
Returns:
list: Clipped values
"""
arr = np.array(data)
# 🧠 TODO
pass
```
---
### 💡 Example
```python
clip_array([-5, -2, 0, 3, 7, 12, 15], 0, 10)
# Expected: [0, 0, 0, 3, 7, 10, 10]
```
---
### 🔑 Key Concepts
- `np.clip(arr, a_min, a_max)` — clips all values in one vectorized call
- `a_min=None` — no lower bound; `a_max=None` — no upper bound
- Clipping on probability outputs: `np.clip(probs, 1e-7, 1 - 1e-7)` avoids `log(0)` in cross-entropy
- `np.clip()` keeps values inside the range unchangedStarter Code
import numpy as np
def clip_array(data, min_val, max_val):
"""
Clip values in an array to the range [min_val, max_val].
Args:
data (list): Input numbers
min_val (number): Minimum value (lower bound)
max_val (number): Maximum value (upper bound)
Returns:
list: Clipped values
"""
arr = np.array(data)
# 🧠 TODO
pass