mardi 6 avril 2021

python random choice with limited replacement

I want to efficiently take samples of an array with limited replacement for each element. A toy example would be

import numpy as np
import random

players = ["alice", "bob"] # two lottery players
tickets_entered = [2, 2] # each one buys two tickets
n_draw = 3 # 3 tickers are drawn
np.random.seed(9)
np.random.choice(players, 3) # choice violates ticket limit
# array(['alice', 'alice', 'alice'], dtype='<U5')
tickets = []
for i, player in enumerate(players):
    for ticket in range(tickets_entered[i]):
        tickets.append(player)
print(tickets)
# ['alice', 'alice', 'bob', 'bob']
random.sample(tickets, n_draw) 

I am working with many players and many tickets, it seems inefficient to have to make a huge array with tickets and then sample from it. What would be the fastest way?




Aucun commentaire:

Enregistrer un commentaire