📘
Array Broadcasting
MediumNumPy Broadcasting
Problem Statement
Perform element-wise operations between arrays of different shapes.
Background
Broadcasting rules:
- Dimensions are compared from right to left
- Dimensions are compatible if equal or one of them is 1
- Arrays are "stretched" to match
Example: (3, 1) + (1, 4) → (3, 4)
Your Task
Write a function broadcast_arrays(row_vec, col_vec) that demonstrates broadcasting.
Given:
- row_vec: Shape (1, n) - a row vector
- col_vec: Shape (m, 1) - a column vector
Output Format
Return a dictionary with:
- "sum": row_vec + col_vec (broadcasts to m×n)
- "product": row_vec * col_vec (broadcasts to m×n)
- "result_shape": Shape of result (as list)
Example:
Input:
row = [[1, 2, 3]], col = [[10], [20]]
Output:
{'sum': [[11, 12, 13], [21, 22, 23]], ...}Reasoning:
Each row_vec element combines with each col_vec element
Constraints:
- row_vec has shape (1, n)
- col_vec has shape (m, 1)
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.