Element-wise Arithmetic and Broadcasting Practice Problem
This data science coding problem helps you practice Mathematical & Statistical Operations, element-wise arithmetic and broadcasting, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Mathematical & Statistical Operations.
- Problem ID: 55
- Problem key: 55-element-wise-arithmetic-and-broadcasting
- URL: https://datacrack.app/solve/55-element-wise-arithmetic-and-broadcasting
- Difficulty: easy
- Topic: Mathematical & Statistical Operations
- Module: NumPy Foundations
Problem Statement
# 🧩 Element-wise Arithmetic and Broadcasting
---
### 🎯 Goal
NumPy's most powerful feature is **vectorized operations** — applying math to entire arrays without loops. **Broadcasting** extends this to arrays of different shapes. This problem builds your intuition for both, which is essential for every ML implementation.
---
### 🔍 Element-wise vs Broadcasting
**Element-wise** (same shape):
```python
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
a + b # → [11, 22, 33] — adds pairwise
```
**Broadcasting** (different shapes — scalar or compatible array):
```python
a = np.array([1, 2, 3])
a * 3 # → [3, 6, 9] — scalar broadcast to every element
M = np.array([[1,2,3],[4,5,6]])
M + 10 # → [[11,12,13],[14,15,16]] — scalar broadcast to all
```
---
### 💻 Task
Implement `array_arithmetic(a, b=None, scalar=None, operation=None)` dispatching to the right NumPy operation.
---
### 📥 Input
- `a`, `b`: lists of numbers (same length for element-wise ops)
- `scalar`: a number (for scalar operations)
- `operation`: string — `"add"`, `"divide"`, `"multiply_scalar"`, `"add_scalar"`, `"power"`
### 📤 Output
- Result array as a Python list
---
### 🧩 Starter Code
```python
import numpy as np
def array_arithmetic(a, b=None, scalar=None, operation=None):
"""
Perform element-wise or broadcasting arithmetic on NumPy arrays.
Args:
a (list): First array
b (list): Second array (for element-wise ops)
scalar (number): Scalar value (for broadcasting ops)
operation (str): The operation to perform
Returns:
list: Result as a Python list
"""
arr_a = np.array(a)
# 🧠 TODO:
pass
```
---
### 🔑 Key Concepts
- NumPy operators (`+`, `-`, `*`, `/`, `**`) work element-wise on arrays
- A scalar is automatically broadcast to every element
- No loops needed — NumPy handles iteration internally in optimized C codeStarter Code
import numpy as np
def array_arithmetic(a, b=None, scalar=None, operation=None):
"""
Perform element-wise or broadcasting arithmetic on NumPy arrays.
Args:
a (list): First array
b (list): Second array (for element-wise ops)
scalar (number): Scalar value (for broadcasting ops)
operation (str): The operation to perform
Returns:
list: Result as a Python list
"""
arr_a = np.array(a)
# 🧠 TODO:
pass