Build a multiplication table with NumPy broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `mult_table(n)` that returns the `(n, n)` multiplication table as a NumPy `ndarray`, where the element at `(i, j)` equals `(i+1)*(j+1)`.
Build the table with broadcasting: use `np.newaxis` to turn a 1-D range into a column of shape `(n, 1)`, and multiply it by a row of shape `(1, n)`. Do not use explicit Python loops or `np.outer`.
```python
mult_table(3)
# array([[1, 2, 3],
# [2, 4, 6],
# [3, 6, 9]])
```
```hint Line up the shapes
Write down the shape of each operand before you multiply. NumPy compares shapes starting from the last axis, and an axis of length 1 can stretch to match the other operand.
```
### What a Strong Answer Covers
- One 1-based range turned into a column view and a row view with `np.newaxis`, with no loops and no `np.outer`
- The broadcasting rule that makes `(n, 1)` times `(1, n)` produce `(n, n)`, and whether the operands get copied
- Correct 1-based values, so the first row and the first column both run from 1 to n
- What the function returns for `n = 0`, and how it treats negative or non-integer input
- Time and memory cost of building the table
### Follow-up Questions
- How does `np.newaxis` enable the broadcast here, and what happens if you multiply two 1-D arrays of shape `(n,)` instead?
- What should `mult_table(0)` return, and how would you handle a negative `n`?
- How would you change the function to build a rectangular table, for example rows 1 to 12 against columns 1 to 5?
- What dtype does the result have, and when could the products overflow?
Overview: Write a NumPy function that returns an n by n multiplication table using broadcasting, with no Python loops and no np.outer. It tests how np.newaxis reshapes a 1-D range, how NumPy broadcasting rules combine a column and a row, and how the function handles n equal to zero.