mardi 22 septembre 2020

Python: Sample N random items from list with weights but without repetition

I am creating a type of lottery system where individuals (identifier by unique id) can have multiple tickets into a lottery however once they are picked, they cannot be selected to win again.

Here is my example:

import random
entrants = ['John', 'Jane', 'Cthulhu']
allEntries = []
for entrant in entrants:
    numEntries = random.randint(1, 5)
    print("%s has %d entries" % (entrant, numEntries))
    allEntries.extend([entrant] * numEntries)
print(random.sample(allEntries, k=2))

My idea was to make a list that has entrant's name numEntries times and then select from there. However sometimes the same individual is picked as both winners. Is there a way to have weights for each entrant?

I tried using random.choices() with weights but this can also select the same individual as both winners.

import random
weights = []
for entrant in entrants:
    numEntries = random.randint(1, 5)
    print("%s has %d entries" % (entrant, numEntries))
    weights.extend([numEntries])
print(random.choices(entrants, weights=weights, k=2))



Aucun commentaire:

Enregistrer un commentaire