Reshape a 1-D NumPy array into a matrix with a given number of rows
Quick Overview
Implement a NumPy function that reshapes a 1-D array into a 2-D matrix with a given number of rows while NumPy infers the column count. It tests reshape with -1, row-major fill order, the error on sizes that do not divide evenly, and whether the result is a view or a copy.
Reshape a 1-D NumPy array into a matrix with a given number of rows
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `reshape_to_matrix(a, rows)` that reshapes a 1-D NumPy array `a` into a 2-D array with exactly `rows` rows.
Pass `-1` for the column dimension so NumPy infers it. Do not hard-code or manually compute the column count.
For example:
```python
a = np.arange(12)
reshape_to_matrix(a, 3)
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
```
```hint What -1 needs
Think about what NumPy has to do with the total element count to fill in the missing dimension, and what it can do when the count does not split evenly.
```
### What a Strong Answer Covers
- Uses `-1` so the column count comes from the array length, with no manual arithmetic
- Explains the order in which elements fill the rows
- Says what happens when `a.size` is not divisible by `rows`, and for `rows` of 0
- Knows whether the result shares memory with `a`
### Follow-up Questions
- How would you fill the matrix column by column instead of row by row?
- If `a` were a strided slice such as `a[::2]`, would the result still be a view, and how would you check?
- How would you pad an array whose length does not divide evenly so the function still returns `rows` rows?
Overview: Implement a NumPy function that reshapes a 1-D array into a 2-D matrix with a given number of rows while NumPy infers the column count. It tests reshape with -1, row-major fill order, the error on sizes that do not divide evenly, and whether the result is a view or a copy.