ArnuldOnData
ArnuldOnData

Reputation: 587

Prints words based on their probabilities

PROBLEM STATEMENT:

Write a program that prints "I love" followed by one word: the additional word should be 'dogs' with 80% probability, 'cats' with 10% probability, and 'bats' with 10% probability.Here's an example output:

I love bats

EXAMPLE

The following program prints out the word 'dog' with 20% probability (Python code)

import random
prob = 0.20

if random.random() < prob:
    print('dog')
            

Why does it print 'dog' with 20% probability? The idea is to draw a random value between 0.00 and 1.01 – that's what the function random() in module random does – and to check whether it is less than the required probability value expressed as a decimal number. For example, the probability that the random value falls between 0.00 and 0.50 is 50%. The probability that the value falls between 0.50 and 1.0 is also 50%. The probability that it falls between 0.00 and 0.20 is 20%, and so forth. Original exercise on Elements of AI: Building AI, chapter 1


WHAT I CAN'T UNDERSTAND:

I need to print one only word: bats, cats or dogs. How can I print one when both cats and bats have exactly same 10% probability. An if condition can not differentiate between 0.10 and 0.10.

Upvotes: 1

Views: 712

Answers (2)

Jasar Orion
Jasar Orion

Reputation: 686

in the simplestway you can have a list that contains the desired word and print it by a randon key number

from random import randrange
words = ["dog","dog","dog","dog","dog","dog","dog","dog","cats","bats"]
print(words[randrange(10)])

Upvotes: 0

nick
nick

Reputation: 1340

You can think of a stick of length 1. You break the stick into 3 pieces (so that the whole stick is used). The first part is .8 of the length of the stick, the second part is .1 and the last part is .1... Now you draw a random variable with random.random() and see which part of the stick it lands on. So the two .1 probabilities land on different parts of the stick:

r = random.random()
if r < .8:
     print('dogs')
elif r < .9:
     # here we have .1 = .9 - .8
     print('cats')
else:
    # this is the final part of the stick so we know we are in this bit if not in the others
    print('bats')


Edit (thanks to @traal no need for numpy here): Just to be complete about this answer you can also use random to sample from the array at the correct probabilities:

choice = random.choices(["dogs", "cats", "bats"], [.8, .1, .1])

Upvotes: 6

Related Questions