Advanced Shuffling Techniques
Custom Shuffling Strategies
Weighted Shuffling
import random
def weighted_shuffle(items, weights):
"""Shuffle list with custom probability weights"""
shuffled = []
while items:
index = random.choices(range(len(items)), weights=weights)[0]
shuffled.append(items.pop(index))
weights.pop(index)
return shuffled
data = [1, 2, 3, 4, 5]
probabilities = [0.1, 0.2, 0.3, 0.2, 0.2]
result = weighted_shuffle(data.copy(), probabilities.copy())
Shuffling Workflow
graph TD
A[Original List] --> B[Apply Weights]
B --> C[Custom Probabilistic Shuffle]
C --> D[Shuffled Result]
Seeding for Reproducible Shuffles
import random
## Set a fixed seed for reproducible shuffling
random.seed(42)
original_list = [1, 2, 3, 4, 5]
random.shuffle(original_list)
Advanced Shuffling Techniques Comparison
Technique |
Randomness |
Complexity |
Use Case |
Standard Shuffle |
High |
Low |
General purpose |
Weighted Shuffle |
Controlled |
Medium |
Probabilistic selection |
Seeded Shuffle |
Predictable |
Low |
Testing, simulation |
Shuffling Large Datasets
import random
def efficient_large_list_shuffle(large_list):
"""Memory-efficient shuffling for large lists"""
for i in range(len(large_list)-1, 0, -1):
j = random.randint(0, i)
large_list[i], large_list[j] = large_list[j], large_list[i]
return large_list
Cryptographically Secure Shuffling
import secrets
def secure_shuffle(lst):
"""Use secrets module for cryptographically secure shuffling"""
for i in range(len(lst)-1, 0, -1):
j = secrets.randbelow(i + 1)
lst[i], lst[j] = lst[j], lst[i]
return lst
LabEx Pro Tip
When dealing with sensitive data or requiring high-entropy randomness, prefer cryptographically secure shuffling methods over standard random shuffling.
- Use appropriate shuffling technique based on requirements
- Consider memory and computational complexity
- Choose between randomness and predictability
- Optimize for specific use cases