Vectorize Cauchy Matrix With Broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `cauchy(x, y)` for 1-D arrays `x` (length `m`) and `y` (length `n`). Return the `(m, n)` Cauchy matrix `C[i, j] = 1 / (x[i] - y[j])` using pure NumPy broadcasting.
For example:
```python
x = np.array([1., 2., 3.])
y = np.array([0., 5.])
cauchy(x, y)
# array([[ 1. , -0.25 ],
# [ 0.5 , -0.33333333],
# [ 0.33333333, -0.5 ]])
```
```hint Line up the axes
Write down the shape each operand needs so that a single subtraction pairs every `x[i]` with every `y[j]`. Broadcasting stretches any axis of length 1 to match the other operand.
```
### Constraints & Assumptions
- Return shape `(len(x), len(y))`.
- Use broadcasting (for example `np.subtract.outer(x, y)` or `x[:, None] - y[None, :]`). No `for` loops or comprehensions.
- The result must match the loop-based reference elementwise.
### What a Strong Answer Covers
- How the inputs are reshaped so one subtraction produces all `m * n` pairwise differences, and why the result has shape `(m, n)`.
- A loop-free implementation that returns floats whatever numeric dtype the inputs arrive in.
- How the result is checked against the double-loop reference.
- What happens when some `x[i] == y[j]`, and a way to detect or guard against it.
- The time and memory cost of the vectorized version compared with the double loop.
### Follow-up Questions
- What happens when some `x[i] == y[j]`, and how would you guard against it?
- Why is the broadcast version faster than the double loop, and what does it cost in memory?
- How would you produce the matrix if `m * n` float64 values do not fit in memory at once?
Overview: Implement a NumPy function that builds the m by n Cauchy matrix, where each entry is one over the difference of an x value and a y value, with no Python loops. It tests broadcasting and outer operations, handling of division by zero when values collide, and the speed and memory cost of vectorized code.