Possible Duplicates:
Random weighted choice
Generate random numbers with a given (numerical) distribution
I have a list of list which contains a series on numbers and there associated probabilities.
prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
for example in prob_list[0]
the number 1 has a probability of 0.5 associated with it. So you would expect 1 to show up 50% of the time.
How do I add weight to the numbers when I select them?
NOTE: the amount of numbers in the list can vary from 6 - 100
EDIT
In the list I have 6 numbers with their associated probabilities. I want to select two numbers based on their probability.
No number can be selected twice. If "2" is selected it can not be selected again.
I'm going to assume the probabilities all add up to 1. If they don't, you're going to have to scale them accordingly so that they do.
First generate a uniform random variable [0, 1] using
random.random()
. Then pass through the list, summing the probabilities. The first time the sum exceeds the random number, return the associated number. This way, if the uniform random variable generated falls within the range (0.5, 0.75] in your example, 2 will be returned, thus giving it the required 0.25 probability of being returned.Here's a test showing it works:
which outputs:
EDIT: Just saw the edit in the question. If you want to select two distinct numbers, you can repeat the above until your second number chosen is distinct. But this will be terribly slow if one number has a very high (e.g. 0.99999999) probability associated with it. In this case, you could remove the first number from the list and rescale the probabilities so that they sum to 1 before selecting the second number.
Here's something that appears to work and meet all your specifications (and subjectively it seems pretty fast). Note that your constraint that the second number not be the same as the first throws the probabilities off for selecting it. That issue is effectively ignored by the code below and it just enforces the restriction (in other words the probability of what the second number is won't be that given for each number in the
prob_list
).Maybe the problem is just related to the data structure. It would be easier if you had a dictionary instead of a list of lists:
This way, you can obtain the weight corresponding to the number:
This might be what you're looking for. Extension to a solution in Generate random numbers with a given (numerical) distribution. Removes the selected item from the distribution, updates the probabilities and returns
selected item, updated distribution
. Not proven to work, but should give a good impression of the idea.