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?
Your algorithm is correct, how about something more elegant:
import random
my_list = ['A'] * 5 + ['B'] * 5 + ['C'] * 90
random.choice(my_list)
that's fine. more generally, you can define something like:
from collections import Counter
from random import randint
def weighted_random(pairs):
total = sum(pair[0] for pair in pairs)
r = randint(1, total)
for (weight, value) in pairs:
r -= weight
if r <= 0: return value
results = Counter(weighted_random([(1,'a'),(1,'b'),(18,'c')])
for _ in range(20000))
print(results)
which gives
Counter({'c': 17954, 'b': 1039, 'a': 1007})
which is as close to 18:1:1 as you can expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With