Broadcasting Rules in Detail Practice Problem
This data science coding problem helps you practice Broadcasting & Vectorization, broadcasting rules in detail, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Broadcasting & Vectorization.
- Problem ID: 105
- Problem key: 105-broadcasting-rules-in-detail
- URL: https://datacrack.app/solve/105-broadcasting-rules-in-detail
- Difficulty: easy
- Topic: Broadcasting & Vectorization
- Module: NumPy Foundations
Problem Statement
# 🧩 Broadcasting Rules in Detail
---
### 🎯 Goal
Learn how NumPy broadcasting allows arrays with different but compatible shapes to be added together without writing loops.
---
### 🔍 The Three Broadcasting Rules
- Broadcasting is NumPy’s way of performing operations on arrays with different shapes.
- Instead of manually repeating values, NumPy automatically aligns the shapes when possible.
- Shapes are compared from the rightmost dimension.
- Two dimensions are compatible if:
| Rule | Condition | Shape Example |
|:-----|:----------|:--------------|
| 1️⃣ | Same dimension sizes can work together | `(2, 3)` + `(2, 3)` |
| 2️⃣ | A dimension with size `1` can stretch | `(2, 3)` + `(1, 3)` → `(2, 3)` |
| 3️⃣ | If one shape has fewer dimensions, add `1`s to its left first | `(3,)` becomes `(1, 3)` before comparing with `(2, 3)` |
Example:
```python
a = [[1, 2, 3],
[4, 5, 6]]
b = [10, 20, 30]
```
Step 1: NumPy pads `b` from shape `(3,)` to `(1, 3)`.
```python
[10, 20, 30] → [[10, 20, 30]]
```
Step 2: NumPy stretches `b` from shape `(1, 3)` to `(2, 3)`.
```python
[[10, 20, 30]] → [[10, 20, 30],
[10, 20, 30]]
```
Step 3: NumPy adds the arrays element by element.
```python
[[1, 2, 3], [[10, 20, 30],
[4, 5, 6]] + [10, 20, 30]]
```
Result:
```python
[[11, 22, 33],
[14, 25, 36]]
```
---
### 💻 Task
Implement `broadcast_add(a, b)` that adds two arrays using NumPy broadcasting. The function should handle arrays of any compatible shape.
---
### 📥 Input
- `a`: list (1D or 2D array)
- `b`: int/float or list (scalar, 1D, or 2D array)
### 📤 Output
- The broadcasted sum as a nested Python list
---
### 🧩 Starter Code
```python
import numpy as np
def broadcast_add(a, b):
"""
Add two arrays using NumPy broadcasting.
Args:
a: First array (list, 1D or 2D)
b: Second array (scalar, list, 1D or 2D)
Returns:
list: Broadcasted sum as a Python list
"""
# 🧠 TODO: Convert a and b to NumPy arrays (dtype=float)
# 🧠 TODO: Add them together — NumPy handles broadcasting
# 🧠 TODO: Return the result as .tolist()
pass
```
---
### 💡 Example
```python
broadcast_add([[1, 2, 3], [4, 5, 6]], [10, 20, 30])
# Expected: [[11.0, 22.0, 33.0], [14.0, 25.0, 36.0]]
broadcast_add([1, 2, 3], 10)
# Expected: [11.0, 12.0, 13.0]
```
---
### 🔑 Key Concepts
- Broadcasting happens **automatically** — no explicit reshaping needed for compatible shapes
- Shapes are compared from the **rightmost** dimension
- A dimension of size **1** is stretched to match the other array's size
- Broadcasting avoids copying the stretched array during alignment, making operations memory-efficient
- If shapes are incompatible (e.g., `(3,)` + `(4,)`), NumPy raises a `ValueError`