Calculate and apply probability in python 3.6


I'm doing a script, and I've been stuck in one step.

My question is this:

Suppose that I have the variable prob = 0.8 , what I want is that prob is the variable that you choose between two objects. Example:

prob = 0.8
perro = "Soy un perro"
gato = "Soy un gato"

If prob is 0.8, it means that there is a 80% chance that the dog variable is chosen, and 20% that the cat is chosen.

Sorry if I did not include any example script, but I did not know how to ask it.

Regards, thanks.

asked by Nexobeta28 YT 19.06.2018 в 17:06

1 answer


On the Python base side, you have no way to set the probability of any of the random functions but nothing prevents you from using a way to simulate a specific probability, which is to work with a List that respects said distribution. In your example, it could be a list with 80 values "I am a dog" and 20 "I am a cat", then use random.choice() to get one or more values from that list. For example:

import random

perro = "Soy un perro"
gato = "Soy un gato"
prob = 0.8
cant = 100
lista = [perro]*int(prob*cant)+[gato]*int((1-prob)*cant)

resultados = {perro: 0, gato: 0}
for i in range(1000):
  resultados[random.choice(lista)] +=1

prob_perro = (100*resultados[perro])/(resultados[gato] + resultados[perro])
print("Verificamos que probabilidad de {0} es de: {1}%".format(perro, prob_perro))

Doing this: cant = 100; lista = [perro]*int(prob*cant)+[gato]*int((1-prob)*cant) we generate a list with 100 values, 80 for "dog" and 20 for "cat", the number of cases will depend on the probabilities in this example of 80/20 with 100 values quickly we come to verify said probability empirically simulating up to 1000 cases of selection of a random element.

On the numpy side if you have a useful way to set the odds that is using numpy.random.choice() for example:

# Para generar 100 valores aleatorios con una probabilidad 80/20 
print(numpy.random.choice([perro, gato], size = 100, p=[0.8,0.2]))

With size we indicate how many values we want to recover randomly and with p we indicate a probability list for each initial value.

answered by 19.06.2018 / 17:26