r/learnpython • • 5h 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

0 Upvotes

21 comments sorted by

5

u/Umustbecrazy 4h ago

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

randnum = random.random()

Compare randnum to your probabilities.

1

u/Purple4cloud7 4h ago

But how come the github code works which calls it 2 times aswell? I understand how it can impact the result but i dont see how the other program is excempt from that issue

4

u/glglgl-de 4h ago

Simple answer: that code is wrong as well.

1

u/Purple4cloud7 4h ago

So i guess the authorizer is just easily foolable😂 feels good to be able to say that. Ive fooled it previously so i had my ideas but i wanted to verify

1

u/glglgl-de 4h ago

Which authorizer?

•

u/KidTempo 12m ago

Probably a script which runs OPs code and assesses whether it generates the right results.

11

u/PeaAble4127 5h 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.

1

u/Fred776 4h ago

So does the other code that op posted

1

u/seanv507 4h ago

In particular, you are doing if random number A < . 8 then dog Else if random number B < . 9 then cat

Assign the random number to a variable to fix it and then do the if statements on that variable

3

u/pdpi 4h ago

The issue is that you’re calling random twice.

See it this way: flip a coin. Heads you like dogs, tails you like cats. The way you wrote it, heads you like dogs, tails you flip another coin that decides whether you like cats or bats.

2

u/jamesfowkes 4h ago

The other code you've posted doesn't work either, for the same reason others have said. It generates slightly too many dogs, slightly too few cats.

1

u/zanfar 4h ago

The first function chooses "cats" 20% (not < 0.8) of 90% (< 0.9) of the time,
the second chooses "cats" 90% (not < 0.1) of 10% (> 0.9).

You don't have equivalent probabilities.

1

u/RagingGods 3h ago

Both are technically wrong, but yours will result in more skewed results. The github example is less skewed so it probably fell within the acceptable range of values the authorizer allows.

For yours, first if condition ensures "dogs" is printed about 80% of the time. That means the remaining 20% will move to the next elif. 90% of the remaining 20% will result in "cats", so about 18% of the original. That leaves the remaining "bats" to be at 2%. That's very far from the intended 80/10/10 split.

The example code ensures 10% will be "bats" and 10% of the remaining 90% to be "cats", and the remaining 81% of the original to be "dogs". Their split will be 81/9/10, which is much closer to 80/10/10.

The authorizer is probably coded to allow some margin of error (for randomness) so the 1% difference fell within the accepted range. Your solution, however, leaves about 8% difference.

1

u/RagingGods 3h ago

A simple fix would be changing your cats probability to 50%.

Since the cats and bats share the same probability, that means that in the event where "dogs" is not selected, then it'll be a 50/50 split between "cats" and "bats".

You can look more into it at "Conditional Probability".

1

u/brasticstack 2h ago edited 2h ago

Just doing the math from the example:

if random.random() < prob:
    favourite = "bats" 

p_bats = 0.10 (technically 0.999... to the limit of float digits in your Python)

elif random.random() >= (1-prob):
    favourite = "cats"

The elif means we're combining probabilities, which is multiplicative:

p_cats = 0.1 * (1 - 0.1) = 0.09

The probabilities must add up to 1, so 

p_dogs = 1 - 0.1 - 0.09 = 0.81 which is close enough for their checker.

1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 2h ago

Personally I'd use random.choices for this, as it supports weights.

import random

options = ('dogs', 'cats', 'bats')
weights = (8, 1, 1)

# These assertions aren't required, I just felt like adding them
assert len(options) == len(weights)
assert sum(weights) % 10 == 0

def main():
    favourite = random.choices(options, weights)[0]
    print(f"I love {favourite}")

main()

1

u/aiuniverse-3p3_here 4h ago

oh ypu are doing a course haha honestly bro both codes actually have the exact same bug the github one just got lucky with the math

basically when u call random.random() twice python generates two totally different random numbers instead of checking the same one in your code first if checks if its < 0.80 (80% dogs). when that fails which happens 20% of the time your elif rolls a brand new number and checks if its < 0.90. so 90% of that remaining 20% becomes cats... which is 0.20 * 0.90 = 18% cats and only 2% bats lol thats why the grader is complaining the github code does the same double roll thing but since they put the 10% checks first, the math works out to 10% bats 9% cats (0.90 * 0.10), and 81% dogs its super close to 80/10/10 so the automated test just lets it pass

just save the random number in a variable at the top so it only rolls once:

python

r = random.random()
if r < 0.80:
    favourite = "dogs"
elif r < 0.90:
    favourite = "cats"
else:
    favourite = "bats"

0

u/GnPDingo 4h ago

Two things i notice here. Your probabilities should total together to 1 And youre making a new random number on every check.

Make one random number by setting it to a variable then compare that number to all 3.

To test your code run a for loop 10 times. You should expect 8 dogs give or take 1 on every print

1

u/Purple4cloud7 4h ago

Yes i see how calling the random function can be problematic. But the other program also calls it 2 times aswell. I dont see how it is excempt from this issue. But with the total should be one. The random.random functions generates a number between 0.0 and 1.0 so im not worried about the last check missing any numbers between 0.9 and 1.0. Am i wrong in that assumption?

0

u/aiuniverse-3p3_here 4h ago

oh ypu are doing a course haha honestly bro both codes actually have the exact same bug the github one just got lucky with the math

basically when u call random.random() twice python generates two totally different random numbers instead of checking the same one in your code first if checks if its < 0.80 (80% dogs). when that fails which happens 20% of the time your elif rolls a brand new number and checks if its < 0.90. so 90% of that remaining 20% becomes cats... which is 0.20 * 0.90 = 18% cats and only 2% bats lol thats why the grader is complaining the github code does the same double roll thing but since they put the 10% checks first, the math works out to 10% bats 9% cats (0.90 * 0.10), and 81% dogs its super close to 80/10/10 so the automated test just lets it pass

just save the random number in a variable at the top so it only rolls once:

python

r = random.random()
if r < 0.80:
    favourite = "dogs"
elif r < 0.90:
    favourite = "cats"
else:
    favourite = "bats"

1

u/Purple4cloud7 4h ago

Oh now i get it. On the elif statement they couldve even copied the if statement since all you need is 2x 10% chances of being ”caught” before reaching dogs😂