vendredi 23 octobre 2020

How to get a random number from a list by setting some probability in python 3? [duplicate]

I have a list in my python 3 code it seems something like this - >

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

I am changing the list regularly so I am using - random.choice(board) instead of looping with len(board) to get a random value from the list. But the problem arises that I need to set some probability from which the choices will be made such as 5 should have maximum probability then followed by 1 , 3 , 7 , 9 of equal probability and remaining with least probability. To do this I found two ways - 1) We can predefine the probability of numbers and then check if they are available in list or 2) We can check for the numbers in list and select the one with highest probability. I hope you are understanding..

Following is my current code -

import random
board = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]

def choose_random():
    return(random.choice(board))

#here I need to return number according to their ranking in probability table
#like 5 - 0.3 
      1 , 3 , 7 , 9 - 0.15
      2 , 4 , 6 , 8 - 0.025
#Remember - It is not compulsory that all of the number from 1-9 will be present in array, cause some 
#numbers are being removed periodically, so you may need to put a check which will confirm if the 
#number.

I think its a bit confusing.. For any clarification pls ask in comments. Any sort of help will be appreciated. Thanks ! is even present in array or not.




Aucun commentaire:

Enregistrer un commentaire