r/learnpython • • 12m ago

I dont know whats different between these two functions

Im doing a course called building ai where were now working with probabilities. I thought it would be very simple but for some reason only the code that i find on github actually goes through the in-built authorizer.

The exercise wants me to ”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.”

Heres my code
import random

def main():
dogs = 0.80
cats = 0.90
bats = 1.00
if random.random() < dogs:
favourite = "dogs" # change this
elif random.random() < cats:
favourite = "cats" # change this
else:
favourite = "bats" # change this

print("I love " + favourite)

main()

The authorizer tells me im printing too many cats. Ive tried changing the comparisons to <= to make cats less probable but without any luck

Heres an example code i found on github through this link
https://github.com/Qianqianxia0910/Building-AI/blob/main/Exercise%204-%20Probabilities.py

import random

def main():
prob = 0.10

if random.random() < prob:
favourite = "bats"
elif random.random() >= (1-prob):
favourite = "cats"
else:
favourite = "dogs"

print("I love " + favourite)

main()

This code goes through flawlessly while in my eyes doing basically the same thing. Any explanation on what could be systematically different between these functions would be nice. Ive gone forward with the course but im just mighty curious on what might be different between these functions

1 Upvotes

2 comments sorted by

•

u/PeaAble4127 5m ago

You are generating a new number in each comparison. You need to reuse the result of the first random call, since you are defining your probabilities cumulatively.

•

u/Umustbecrazy 0m ago

Call random.random once, you get a new value each time the method is called.

randnum = random.random()

Compare randnum to your probabilities.