Build an n x n NumPy matrix with a border of ones and zeros inside
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `border_matrix(n)` that returns an `n x n` NumPy array whose outer border is `1` and interior is `0`.
Requirements:
- Create the array with `np.ones((n, n))`.
- Zero the interior with one slice assignment.
- No explicit Python loops.
Example:
```python
border_matrix(4)
# array([[1., 1., 1., 1.],
# [1., 0., 0., 1.],
# [1., 0., 0., 1.],
# [1., 1., 1., 1.]])
```
```hint One slice per axis
Find a slice that leaves out exactly the first and last index of an axis, then check what it selects when the axis has only one or two elements.
```
### Constraints & Assumptions
- `n` is a positive integer (`1 <= n`).
- For `n <= 2` the result is all `1`.
### What a Strong Answer Covers
- Allocates the array once and zeroes the interior with a single slice assignment on both axes, with no loops.
- Explains why the chosen slice covers exactly the cells that are not on the border.
- Traces `n = 1` and `n = 2` and shows that no special case is needed.
- Notes the dtype that `np.ones` produces and how to get integers instead.
### Follow-up Questions
- How would you make the border `k` cells thick, and what goes wrong at `k = 0`?
- How would you build the same frame starting from `np.zeros` and setting only the border?
- How would you draw the frame on every matrix in a batch of shape `(b, n, n)` without a loop?
Overview: Write a NumPy function that returns an n by n array with ones on the outer border and zeros inside, using one slice assignment and no loops. It tests negative-index slicing, small cases such as n equal to 1 or 2, and the dtype that np.ones produces.