I'm trying to build a lottery-like game in Python 3.6 where a function selects a winner from a participant list where every participant has a winning chance weighted by the value of the tickets they bought. I'm using the SystemRandom class in order to avoid software-state-dependency. Is this a good practice regarding good enough randomness? How could this code be improved? Also, does the shuffling does add anything to the randomness?
import random
# Randomly selects an element from a choice list using weighted probabilities
def randomWeightedSelection(choices, weights):
# Build index list
indices = list(range(len(choices)))
# Shuffle indices
random.shuffle(indices)
# Shuffle weights accordingly
shuffled_weights = [weights[i] for i in indices]
# Create random generator
rng = random.SystemRandom()
# Select element
selected_index = rng.choices(indices, weights=shuffled_weights, k=1)[0]
return [choices[selected_index], selected_index]
Aucun commentaire:
Enregistrer un commentaire