Possible Duplicate:
A weighted version of random.choice
Let's say for simplicity a function takes in 4 inputs: 2 names and their respective 'bias/weights', how can I write a function such that it returns either a
or b
at random but still considers those weights into the random outcome.
a = 'x'
b = 'y'
p_a = 10
p_b = 90
def myRand(a, p_a, b, p_b):
return 'x' 10% of the time, 'y' 90% of time
What I've done so far
import random
def myRand(a, p_a, b, p_b):
probs = [a]*p_a + [b]*p_b
return random.choice(probs)
Can someone point why this is an incorrect or not the best answer? My justification is that I'm assuming every element has the same probability of being picked so the outcome should still favor 10:90. Or maybe we can shuffle the array before using random.choice()
?
Is there a better way to do this? Maybe I'm missing something obvious here or is this correct?
Thanks