Advanced Sequence Techniques
Custom Random Sequence Generation
Creating Complex Random Generators
import random
import numpy as np
## Custom random sequence with constraints
def custom_sequence_generator(start, end, exclude=None):
while True:
value = random.randint(start, end)
if exclude is None or value not in exclude:
yield value
Probabilistic Sequence Techniques
Weighted Random Generation
def weighted_random_selection(items, weights):
total = sum(weights)
normalized_weights = [w/total for w in weights]
return random.choices(items, weights=normalized_weights)[0]
items = ['A', 'B', 'C']
weights = [0.5, 0.3, 0.2]
result = weighted_random_selection(items, weights)
Advanced Distribution Methods
Distribution |
Method |
Parameters |
Normal |
random.gauss() |
Mean, Standard Deviation |
Exponential |
random.expovariate() |
Rate |
Poisson |
numpy.random.poisson() |
Lambda |
Sequence Generation Strategies
graph TD
A[Random Sequence Generation] --> B[Uniform Distribution]
A --> C[Constrained Generation]
A --> D[Probabilistic Methods]
A --> E[Custom Algorithms]
Cryptographically Secure Sequences
import secrets
def secure_random_sequence(length, start=0, end=100):
return [secrets.randbelow(end - start + 1) + start
for _ in range(length)]
secure_seq = secure_random_sequence(10)
Efficient Random Sequence Generation
import numpy as np
import timeit
## NumPy vs Standard Random
def numpy_random_generation():
return np.random.randint(0, 100, 1000)
def standard_random_generation():
return [random.randint(0, 100) for _ in range(1000)]
## Performance comparison
numpy_time = timeit.timeit(numpy_random_generation, number=100)
standard_time = timeit.timeit(standard_random_generation, number=100)
Machine Learning Random Techniques
Reproducible Randomness in LabEx
import random
import numpy as np
def set_global_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
## Additional framework seeds if needed
Advanced Sampling Methods
Stratified and Systematic Sampling
def stratified_sample(population, strata_key, sample_size):
stratified_groups = {}
for item in population:
strata = item[strata_key]
if strata not in stratified_groups:
stratified_groups[strata] = []
stratified_groups[strata].append(item)
return {
strata: random.sample(group, min(len(group), sample_size))
for strata, group in stratified_groups.items()
}
Practical Considerations
- Choose appropriate randomization technique
- Consider computational complexity
- Ensure statistical properties meet requirements
- Validate random sequence characteristics