Practical Code Examples
Real-World Scenarios for Random Index Generation
graph TD
A[Practical Applications] --> B[Data Sampling]
A --> C[Machine Learning]
A --> D[Game Development]
A --> E[Scientific Simulation]
Example 1: Random Data Sampling
import random
def sample_dataset(data, sample_size):
"""
Safely sample a subset of data using random indices
Args:
data (list): Original dataset
sample_size (int): Number of samples to extract
Returns:
list: Randomly sampled data
"""
if sample_size > len(data):
raise ValueError("Sample size exceeds dataset length")
indices = random.sample(range(len(data)), sample_size)
return [data[idx] for idx in indices]
## Usage example
original_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sampled_data = sample_dataset(original_data, 4)
print(sampled_data)
Example 2: Machine Learning Data Split
import numpy as np
def train_test_split(X, y, test_size=0.2, random_state=None):
"""
Create train and test splits with random indices
Args:
X (numpy.ndarray): Feature matrix
y (numpy.ndarray): Target variable
test_size (float): Proportion of test data
random_state (int): Seed for reproducibility
Returns:
tuple: Train and test splits
"""
np.random.seed(random_state)
total_samples = len(X)
test_samples = int(total_samples * test_size)
## Generate random indices
indices = np.random.permutation(total_samples)
test_indices = indices[:test_samples]
train_indices = indices[test_samples:]
X_train, X_test = X[train_indices], X[test_indices]
y_train, y_test = y[train_indices], y[test_indices]
return X_train, X_test, y_train, y_test
## Example usage
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
y = np.array([0, 1, 0, 1, 0])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
Technique |
Time Complexity |
Memory Overhead |
random.sample() |
O(k) |
Low |
NumPy Permutation |
O(n) |
Moderate |
Custom Implementation |
Varies |
Depends on approach |
Example 3: Game Randomization
import random
class GameRandomizer:
def __init__(self, total_items):
self.total_items = total_items
self.used_indices = set()
def get_unique_random_index(self):
"""
Generate a unique random index
Returns:
int: Unique random index
"""
available_indices = set(range(self.total_items)) - self.used_indices
if not available_indices:
raise ValueError("No more unique indices available")
index = random.choice(list(available_indices))
self.used_indices.add(index)
return index
## Usage in game context
game_items = ['sword', 'shield', 'potion', 'armor', 'boots']
randomizer = GameRandomizer(len(game_items))
## Generate unique random item selections
for _ in range(3):
random_item_index = randomizer.get_unique_random_index()
print(game_items[random_item_index])
Key Takeaways
- Always validate input parameters
- Consider performance and memory constraints
- Use appropriate random generation techniques
- Implement error handling
By mastering these practical examples, developers using LabEx can create robust random index generation solutions across various domains.