Split a NumPy Array Into n Near-Equal Contiguous Parts
Quick Overview
Divide a 1-D NumPy array into a given number of contiguous pieces whose lengths differ by at most one, without failing on uneven lengths. It tests NumPy splitting functions, remainder handling, views versus copies and edge cases like more pieces than elements.
Split a NumPy Array Into n Near-Equal Contiguous Parts
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `split_into_parts(a, n)` that divides a 1-D NumPy array `a` into `n` contiguous sub-arrays of near-equal length and returns them as a Python `list` of arrays.
The function must:
- Return exactly `n` sub-arrays.
- When `len(a)` is not divisible by `n`, give the first `len(a) % n` sub-arrays one extra element (as `np.array_split` does), without raising.
- Keep the original element order and dtype, and return views of `a`.
Example:
```python
a = np.arange(7)
split_into_parts(a, 3)
# [array([0, 1, 2]), array([3, 4]), array([5, 6])]
```
```hint Uneven lengths
NumPy has more than one splitting function. Check how each behaves when the length is not a multiple of `n`. If you write it by hand, the quotient and remainder of `len(a)` divided by `n` give you every piece's length.
```
### Constraints & Assumptions
- `a` is 1-D.
- `n` is a positive integer.
### What a Strong Answer Covers
- Exactly `n` contiguous pieces whose lengths differ by at most one, with the longer pieces first.
- Lengths that `n` does not divide, handled without an error.
- Whether the pieces are views or copies, and what that means when someone writes to a piece.
- Edge cases such as an empty array or `n` larger than `len(a)`.
### Follow-up Questions
- Why does `np.split` fail here when `np.array_split` works?
- How would you split along a different axis of a 2-D array?
- What does the function return when `n` is larger than `len(a)`?
- How would you split into chunks of a fixed size `k` instead, with a shorter last chunk?
Overview: Divide a 1-D NumPy array into a given number of contiguous pieces whose lengths differ by at most one, without failing on uneven lengths. It tests NumPy splitting functions, remainder handling, views versus copies and edge cases like more pieces than elements.
Implement split_into_parts(a, n) that divides a 1-D NumPy array a into n contiguous sub-arrays of near-equal length and returns them as a Python list of arrays.
The function must:
Return exactly
n
sub-arrays.
When
len(a)
is not divisible by
n
, give the first
len(a) % n
sub-arrays one extra element (as
np.array_split
does), without raising.
Keep the original element order and dtype, and return views of
a
.