Search code examples
pythonlistrandommethodsprobability

Making a choice based on probability - Python


my_list = [1,2,3,4,5,6,7,8,9,10] 

Lets say we have a list like this in Python. I want to continuously print the elements in this list one by one. but I want elements 5 and less than 5 to have an 80% chance of appearing on the screen, and the rest of elements to have a 20% chance of appearing on the screen. How can i do this?


Solution

  • There is almost certainly a better solution that this, but this works. It first works out if its going to be in the 20% or 80% for each round (rand) by saying if the random number is 8 or 9 then its in the 20% (2/10), then randomly selects from the corresponding half of the list.

    import random
    rand = random.randrange(0,9)
    my_list = [1,2,3,4,5,6,7,8,9,10]
    if rand == 8 or rand == 9:
        print(my_list[5:][random.randrange(0,4)])
    else:
        print(my_list[:5][random.randrange(0,4)])