Reshape and Flatten Practice Problem
This data science coding problem helps you practice Array Creation & Attributes, reshape and flatten, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Creation & Attributes.
- Problem ID: 48
- Problem key: 48-reshape-and-flatten
- URL: https://datacrack.app/solve/48-reshape-and-flatten
- Difficulty: easy
- Topic: Array Creation & Attributes
- Module: NumPy Foundations
Problem Statement
# 🧩 Reshape and Flatten
---
### 🎯 Goal
`reshape` is one of the most important NumPy operations in machine learning. Data often arrives in one shape (e.g., a 1D stream of pixels) and needs to be transformed into another (e.g., a 2D image matrix). Understanding reshape prepares you to handle the constant shape manipulation in ML pipelines.
---
### 🔍 The Rule
Reshaping works as long as the **total number of elements stays the same**:
```
[1, 2, 3, 4, 5, 6] → reshape(2, 3) → [[1, 2, 3], [4, 5, 6]]
Total: 6 Total: 2 × 3 = 6 ✓
```
Flattening is just reshaping to 1D.
---
### 💻 Task
Implement `reshape_array(data, new_shape)` using `np.array().reshape()`.
---
### 📥 Input
- `data`: a Python list (any shape)
- `new_shape`: list — the desired shape, e.g., `[2, 3]`
### 📤 Output
- The reshaped array as a nested Python list
---
### 🧩 Starter Code
```python
import numpy as np
def reshape_array(data, new_shape):
"""
Reshape a NumPy array to the specified shape.
Args:
data (list): Input data (any shape)
new_shape (list): Target shape, e.g. [2, 3]
Returns:
list: Reshaped array as a nested Python list
"""
arr = np.array(data)
# 🧠 TODO:
pass
```
---
### 💡 Example
```python
reshape_array([1, 2, 3, 4, 5, 6], [2, 3])
# Expected: [[1, 2, 3], [4, 5, 6]]
reshape_array([[1, 2, 3], [4, 5, 6]], [6])
# Expected: [1, 2, 3, 4, 5, 6] (flatten)
```
---
### 🔑 Key Concepts
- `arr.reshape(-1)` or `arr.flatten()` — both flatten to 1D
- `-1` in shape: NumPy infers that dimension automatically, e.g., `reshape(-1, 3)` means "figure out the number of rows"
- `arr.reshape(new_shape)` does **not** copy data (view), `arr.flatten()` always copiesStarter Code
import numpy as np
def reshape_array(data, new_shape):
"""
Reshape a NumPy array to the specified shape.
Args:
data (list): Input data (any shape)
new_shape (list): Target shape, e.g. [2, 3]
Returns:
list: Reshaped array as a nested Python list
"""
arr = np.array(data)
# 🧠 TODO:
pass