Array Slicing Practice Problem
This data science coding problem helps you practice Indexing, Slicing & Filtering, array slicing, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Indexing, Slicing & Filtering.
- Problem ID: 49
- Problem key: 49-array-slicing
- URL: https://datacrack.app/solve/49-array-slicing
- Difficulty: easy
- Topic: Indexing, Slicing & Filtering
- Module: NumPy Foundations
Problem Statement
# 🧩 Array Slicing
---
### 🎯 Goal
NumPy slicing is the foundation of all data selection. Before you learn Pandas `.loc[]` and `.iloc[]`, you need fluency in NumPy's slice notation — including 1D slicing, 2D (row, column) slicing, and reverse slicing.
---
### 🔍 Slice Notation: `start:stop:step`
**1D array:**
```python
arr = np.array([10, 20, 30, 40, 50])
arr[1:4] # → [20, 30, 40] (indices 1,2,3)
arr[::2] # → [10, 30, 50] (every 2nd)
arr[::-1] # → [50, 40, 30, 20, 10] (reversed)
```
**2D array (matrix):**
```python
M[row_start:row_stop, col_start:col_stop]
M[:2, 1:3] # first 2 rows, cols 1 and 2
```
---
### 💻 Task
Implement two functions:
1. `slice_1d(data, start, stop, step)` — slice a 1D array
2. `slice_2d(data, row_start, row_stop, col_start, col_stop)` — slice a 2D array
The test harness calls either function based on which parameters are provided.
---
### 📥 Input
For 1D slicing:
- `data`: list of numbers
- `start`, `stop`, `step`: int
For 2D slicing:
- `data`: 2D list (matrix)
- `row_start`, `row_stop`, `col_start`, `col_stop`: int
### 📤 Output
- Sliced array as a Python list
---
### 🧩 Starter Code
```python
import numpy as np
def slice_data(data, **kwargs):
"""
Handle array slicing for both 1D and 2D arrays in one function.
Automatically detects dimensions and calls the appropriate slicer.
"""
arr = np.array(data)
def slice_1d(arr, start, stop, step):
# 🧠 TODO:
def slice_2d(arr, row_start, row_stop, col_start, col_stop):
# 🧠 TODO:
if arr.ndim == 1:
return slice_1d(arr, kwargs['start'], kwargs['stop'], kwargs['step'])
elif arr.ndim == 2:
return slice_2d(arr, kwargs['row_start'], kwargs['row_stop'], kwargs['col_start'], kwargs['col_stop'])
else:
raise ValueError("Only 1D and 2D arrays are supported.")
# Example usage:
# res_1d = slice_data([1, 2, 3, 4, 5], 0, 3, 1)
# res_2d = slice_data([[1, 2], [3, 4]], 0, 1, 0, 1)
```
---
### 🔑 Key Concepts
- `step = -1` reverses the array
- In 2D: `arr[rows, cols]` — rows and columns are separate slice axes
- `arr[0, :]` = first row (all columns); `arr[:, 0]` = first column (all rows)Starter Code
import numpy as np
def slice_data(data, **kwargs):
"""
Handle array slicing for both 1D and 2D arrays in one function.
Automatically detects dimensions and calls the appropriate slicer.
"""
arr = np.array(data)
def slice_1d(arr, start, stop, step):
# 🧠 TODO:
def slice_2d(arr, row_start, row_stop, col_start, col_stop):
# 🧠 TODO:
if arr.ndim == 1:
return slice_1d(arr, kwargs['start'], kwargs['stop'], kwargs['step'])
elif arr.ndim == 2:
return slice_2d(arr, kwargs['row_start'], kwargs['row_stop'], kwargs['col_start'], kwargs['col_stop'])
else:
raise ValueError("Only 1D and 2D arrays are supported.")
# Example usage:
# res_1d = slice_data([1, 2, 3, 4, 5], 0, 3, 1)
# res_2d = slice_data([[1, 2], [3, 4]], 0, 1, 0, 1)