Flatten and Ravel Arrays
Problem Statement
Convert a multi-dimensional array to 1D using flatten() and ravel().
Background
Both flatten() and ravel() convert arrays to 1D:
- flatten(): Always returns a copy
- ravel(): Returns a view when possible (more memory efficient)
Your Task
Write a function flatten_array(arr) that:
- Flattens the input array
- Returns a dictionary with:
- "original_shape": Original shape as list
- "flattened": Flattened array as list
- "size": Total number of elements
Output Format
Return a dictionary with exactly these three keys.
Example:
[[1, 2, 3], [4, 5, 6]]
{'original_shape': [2, 3], 'flattened': [1, 2, 3, 4, 5, 6], 'size': 6}2x3 array has 6 elements when flattened
Constraints:
- Use flatten() or ravel()
- Input can be any dimensional array
1. Background Knowledge
NumPy arrays are the foundational data structure for numerical computing in Python, enabling efficient multi-dimensional array operations. Flattening converts any N-dimensional array into a 1D array by reshaping elements in row-major (C-order) order, preserving all data in a contiguous sequence.
Key methods:
- arr.flatten(): Always creates a copy of the data (safe but memory-intensive).
- arr.ravel(): Returns a view (references original data) when possible, falling back to copy only if needed (memory-efficient).
Memory concepts:
View: Shared memory reference → O(1) space, modifies original
Copy: Independent duplicate → O(n) space, safe from side effects
Total elements: n=\prod(\text{shape}), accessed via arr.size.
2. Algorithm Approach
Core technique: Use NumPy's flattening + metadata extraction.
Input: ndarray arr (any shape)
1. Extract shape: arr.shape → tuple → list
2. Flatten: arr.flatten() or arr.ravel() → 1D ndarray
3. Convert to list: flattened.tolist()
4. Compute size: arr.size (or len(flattened))
5. Package: dict with 3 keys
Flatten vs Ravel decision:
| Method | Memory | When to use |
|---|---|---|
| flatten() | Always copy | Safety-critical, no original modification |
| ravel() | View if possible | Memory optimization (recommended here) |
Both yield identical logical results but differ in implementation.
3. Step-by-Step Strategy
def flatten_array(arr):
# Step 1: Capture metadata
original_shape = list(arr.shape) # Convert tuple → list
total_size = arr.size # O(1) property access
# Step 2: Flatten (use ravel() for efficiency)
flattened = arr.ravel() # View when possible
# Step 3: Convert to required types
flattened_list = flattened.tolist() # ndarray → Python list
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.