Search code examples
pythonprobability

Is there a way to pick a random number of elements from a list with independent probabilities in Python?


I wish to pick a random number of elements (can be 0 too) from a list in python. The probability of choosing any element is independent of others. For example:

example_list = ['Apple', 'Orange', 'Kiwi', 'Mango']
example_probabilties = [6, 9, 1, 4]

I wish to pick out a random number of fruits, where the element 'Apple' has a probability of 6% of being chosen, 'Orange' has a 9% probability of being picked, and so on.

As far as I understand, random.choices() uses the weights differently, essentially treating the probabilities in this manner:

Probability of choosing 'Apple': 6/sum(example_probabilities)
Probability of choosing 'Orange': 9/sum(example_probabilities)

And so on...

Is there any other way I can achieve the desired result?


Solution

  • Since each choice is independent of others, each should be picked independently. The main question is how to add e.g. an apple to the choices with 6% chance. This can be done by picking a random number from 0 to 1 (random.random()) and checking if it is less than 0.06 (i.e. 6%).

    Then, the solution can be applied to the whole list:

    fruits = ['Apple', 'Orange', 'Kiwi', 'Mango']
    percentages = [6, 9, 1, 4]
    probabilities = [p / 100 for p in percentages]
    
    results = [
        fruit
        for fruit, prob in zip(fruits, probabilities)
        if prob > random.random()
    ]