Parallel Random Generation Practice Problem
This data science coding problem helps you practice Random Sampling & Generators, parallel random generation, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Random Sampling & Generators.
- Problem ID: 114
- Problem key: 114-parallel-random-generation
- URL: https://datacrack.app/solve/114-parallel-random-generation
- Difficulty: medium
- Topic: Random Sampling & Generators
- Module: NumPy Foundations
Problem Statement
# 🧩 Parallel Random Generation
---
### 🎯 Goal
In parallel or multi-worker code, using one shared random generator can make results depend on call order. The `rng.spawn(n)` method creates `n` independent child generators from one parent generator, so each worker gets its own random stream.
---
### 🔍 Example
```python
rng = np.random.default_rng(42)
child_rngs = rng.spawn(2)
print(child_rngs[0].random(2))
print(child_rngs[1].random(2))
```
---
### 💻 Task
Implement `generate_parallel_streams(seed, num_workers, size)` that uses `np.random.default_rng(seed)` to spawn `num_workers` child generators, and returns a list of `size` random floats for each worker.
---
### 📥 Input
- `seed`: int
- `num_workers`: int
- `size`: int
### 📤 Output
- A list containing `num_workers` lists, each with `size` random floats.
---
### 🧩 Starter Code
```python
import numpy as np
def generate_parallel_streams(seed, num_workers, size):
"""
Spawn child generators for parallel streams.
"""
# 🧠 TODO: Create a parent generator
# 🧠 TODO: Spawn child generators
# 🧠 TODO: Return a list of random float lists
pass
```
---
### 💡 Expected Output
```python
generate_parallel_streams(42, 2, 2)
# Expected: [[0.916..., 0.910...], [0.467..., 0.046...]]
```
---
### 🔑 Key Concepts
- `spawn(n)` creates child generators that are independent with very high probability, which is the NumPy-recommended pattern for parallel random streams.
Starter Code
import numpy as np
def generate_parallel_streams(seed, num_workers, size):
"""
Spawn child generators for parallel streams.
"""
# 🧠 TODO: Create a parent generator
# 🧠 TODO: Spawn child generators
# 🧠 TODO: Return a list of random float lists
pass