Back to Practice
#0075

Add Column Offsets With Broadcasting

EasyNumPy15 min15 XP

Problem

Given a 2D NumPy array matrix and a 1D array offsets whose length equals the number of columns, return matrix + offsets.

Why This Matters

Broadcasting is what makes NumPy concise and fast. Understanding shape alignment prevents mysterious errors.

Function Signature

def add_column_offsets(matrix, offsets):

Examples

Example 1
Input[[1,2,3],[4,5,6]] + [10,20,30]
Output[[11,22,33],[14,25,36]]

The offset vector is applied to each row.

Constraints

  • matrix is 2D.
  • offsets length equals number of columns.
  • Return a NumPy array.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Two rows three columns
Inputnp.array([[1,2,3],[4,5,6]]), np.array([10,20,30])
Expected[[11,22,33],[14,25,36]]

The 1D offsets broadcast across rows.

Hidden Test Categories
single rownegative offsetsfloat values