Shuffle an Array Practice Problem
This data science coding problem helps you practice Random Sampling & Generators, shuffle an array, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Random Sampling & Generators.
- Problem ID: 119
- Problem key: 119-shuffle-an-array
- URL: https://datacrack.app/solve/119-shuffle-an-array
- Difficulty: easy
- Topic: Random Sampling & Generators
- Module: NumPy Foundations
Problem Statement
# 🧩 Shuffle an Array
---
### 🎯 Goal
Shuffling is a fundamental operation in ML: shuffling training data before each epoch, creating random splits, and randomizing experiment order. `np.random.permutation` returns a **new shuffled copy** of an array (unlike `np.random.shuffle` which modifies in-place). This problem teaches you to create a shuffled copy while preserving the original elements.
---
### 🔍 Shuffling with `permutation` vs `shuffle`
```python
data = [1, 2, 3, 4, 5]
# permutation — returns new array (original unchanged)
shuffled = np.random.permutation(data)
# shuffle — modifies in-place (returns None)
arr = np.array(data)
np.random.shuffle(arr) # arr is now shuffled
```
| Function | Returns | Modifies original? |
|:---------|:--------|:--------------------|
| `np.random.permutation(x)` | New shuffled array | No |
| `np.random.shuffle(x)` | `None` | Yes (in-place) |
---
### 💻 Task
Implement `shuffle_array(data, seed)` that returns a shuffled copy of the input array.
---
### 📥 Input
- `data`: list of numbers
- `seed`: int — random seed
### 📤 Output
- A shuffled list containing the same values in randomized order.
---
### 🧩 Starter Code
```python
import numpy as np
def shuffle_array(data, seed):
"""
Shuffle an array.
Args:
data (list): Input array
seed (int): Random seed
Returns:
list: Shuffled copy of the input array
"""
# 🧠 TODO: Set up reproducible randomness
# 🧠 TODO: Create a shuffled copy of the data
# 🧠 TODO: Return it as a list
pass
```
---
### 💡 Example
```python
shuffle_array([1, 2, 3, 4, 5], 42)
# Expected: [2, 5, 3, 1, 4]
```
---
### 🔑 Key Concepts
- A correct shuffle **preserves all elements** — only the order changes.
- You can verify preservation by checking `sorted(shuffled) == sorted(data)`.
- Prefer `np.random.permutation()` over `np.random.shuffle()` to avoid modifying the original data.Starter Code
import numpy as np
def shuffle_array(data, seed):
"""
Shuffle an array.
Args:
data (list): Input array
seed (int): Random seed
Returns:
list: Shuffled copy of the input array
"""
# 🧠 TODO: Set up reproducible randomness
# 🧠 TODO: Create a shuffled copy of the data
# 🧠 TODO: Return it as a list
pass