Based on an answer to the question about generating discrete random variables with specified weights, you can use numpy.random.choice
to get 20 times faster code than with random.choice
:
from numpy.random import choice
sample = choice(['apple','orange','mango'], p=[0.4, 0.3, 0.3], size=1000000)
from collections import Counter
print(Counter(sample))
Outputs:
Counter({'apple': 399778, 'orange': 300317, 'mango': 299905})
Not to mention that it is actually easier than "to build a list in the required proportions and then shuffle it".
Also, shuffle would always produce exactly 40% apples, 30% orange and 30% mango, which is not the same as saying "produce a sample of million fruits according to a discrete probability distribution". The latter is what both choice
solutions do (and the bisect
too). As can be seen above, there is about 40% apples, etc., when using numpy
.