Build a 5x5 structured NumPy array of meshgrid coordinates over the unit square
Quick Overview
Build a 5x5 NumPy structured array whose x and y fields hold meshgrid coordinates over the unit square. It tests structured dtypes, meshgrid indexing order, and how a record layout in memory differs from keeping each coordinate in its own array.
Build a 5x5 structured NumPy array of meshgrid coordinates over the unit square
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `build_grid()`. It returns a structured NumPy array of shape `(5, 5)` with float fields `'x'` and `'y'` that hold `X` and `Y` from `X, Y = np.meshgrid(lin, lin)`, where `lin = np.linspace(0, 1, 5)`.
Requirements:
- The result has shape `(5, 5)` and a structured dtype with float fields `'x'` and `'y'`.
- `result['x']` equals `X` and `result['y']` equals `Y`.
- Use the default Cartesian (`'xy'`) meshgrid indexing.
Example:
```python
arr = build_grid()
arr.shape # (5, 5)
arr.dtype # dtype([('x', '<f8'), ('y', '<f8')])
arr['x'][0] # [0. , 0.25, 0.5 , 0.75, 1. ]
arr['y'][:, 0] # [0. , 0.25, 0.5 , 0.75, 1. ]
```
```hint Declaring the fields
A structured dtype can be written as a list of (name, type) pairs, and each field of a structured array can be read or assigned by its name.
```
```hint Which axis varies
With the default indexing, work out whether `X` changes along the rows or along the columns before you compare against the example.
```
### What a Strong Answer Covers
- Building the 1-D axis and the two coordinate grids with the indexing the task specifies
- Declaring a structured dtype with two float fields and filling each field from its grid
- Checking which field varies along rows and which along columns, against the example
- How the record layout of a structured array affects reading one field
### Follow-up Questions
- How would you generalize this to N points and an arbitrary set of named coordinate fields?
- What is the memory layout of a structured array versus two separate arrays?
- What changes in the result if you pass `indexing='ij'` to `np.meshgrid`?
Overview: Build a 5x5 NumPy structured array whose x and y fields hold meshgrid coordinates over the unit square. It tests structured dtypes, meshgrid indexing order, and how a record layout in memory differs from keeping each coordinate in its own array.
Implement build_grid(). It returns a structured NumPy array of shape (5, 5) with float fields 'x' and 'y' that hold X and Y from X, Y = np.meshgrid(lin, lin), where lin = np.linspace(0, 1, 5).
Requirements:
The result has shape
(5, 5)
and a structured dtype with float fields
'x'
and
'y'
.
result['x']
equals
X
and
result['y']
equals
Y
.
Use the default Cartesian (
'xy'
) meshgrid indexing.