Equal-Width Feature Binning
~15 mincode completion
Implement bin_features(arr, n_bins) that returns an integer array of bin indices in [0, n_bins - 1].
Examples
Range [0,4] split into 2 bins: values below 2 and at-or-above 2
- Input
- bin_features([0, 1, 2, 3, 4], 2)
- Output
- [0, 0, 1, 1, 1]
Range [0,20] split into 4 bins of width 5
- Input
- bin_features([0, 5, 10, 15, 20], 4)
- Output
- [0, 1, 2, 3, 3]
All identical values: zero-range edge case returns all zeros
- Input
- bin_features([7, 7, 7], 3)
- Output
- [0, 0, 0]
Hints
Hint 1
Work directly with the arguments arr, n_bins and return the result rather than printing it.
Hint 2
Watch for this: included both boundary edges in digitize causing off by one.
Requirements
arr: 1D float arrayn_bins: Number of equal-width binsReturn Integer array of bin indices in [0, n_bins - 1].
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~15 min
••••••••••••••••
8 employers weight this skill
3 big tech firms, 2 AI product companies, 1 defense company, 1 enterprise vendor, 1 quant fund. Top match scores 87.
Python
import numpy as np
def bin_features(arr: np.ndarray, n_bins: int) -> np.ndarray:
"""
Assign each value in arr to an equal-width bin (0-indexed).
Args:
arr: 1D float array
n_bins: Number of equal-width bins
Returns:
Integer array of bin indices in [0, n_bins - 1].
"""
# YOUR CODE HERE
pass