vendredi 22 avril 2022

How to generate a list of lists using probabilities for each element in Python

I want to verify if i am doing things right, the question is : The function random, without arguments, assumed to be imported, returns a random real of the interval [0,1[. Write a function init(N) taking as input a strictly positive integer, and returning a grid (NxN) (in the form of a list of lists), each cell containing a cell with a value of True with a probability of 1/3. For example:

init(4) => [[True, False, False, False],[False, False, True, True],[False,False,False,False],[True,False, True, False]]

from random import random
def init(N):
    return [ [True if random()<1/3 else False  for j in range(N)] for i in range (N) ]
print(init(4))

I am confused is the probablity 1/3 means that the generated random value is less than 1/3 or it is referring to a weighted probability such the one used in random.choice




Aucun commentaire:

Enregistrer un commentaire