This question already has an answer here:
- A weighted version of random.choice 20 answers
I need to return different values based on a weighted round-robin such that 1 in 20 gets A, 1 in 20 gets B, and the rest go to C.
So:
A => 5%
B => 5%
C => 90%
Here's a basic version that appears to work:
import random
x = random.randint(1, 100)
if x <= 5:
return 'A'
elif x > 5 and x <= 10:
return 'B'
else:
return 'C'
Is this algorithm correct? If so, can it be improved?
that's fine. more generally, you can define something like:
which gives
which is as close to 18:1:1 as you can expect.
It seems correct since you are using a
uniform
random variable with independent draws the probability for each number will be1/n
(n=100).You can easily verify your algorithm by running it say 1000 time and see the frequency for each letter.
Another algorithm you might consider is to generate an array with your letters given the frequency you want for each letter and only generate a single random number which is the index in the array
It will be less efficient in memory but should perform better
Edit:
To respond to @Joel Cornett comment, an example will be very similar to @jurgenreza but more memory efficient
If you want to use weighted random and not percentile random, you can make your own Randomizer class:
Your algorithm is correct, how about something more elegant: