r/learnpython • • 4d 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

2 Upvotes

30 comments sorted by

6

u/Umustbecrazy 4d 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 4d 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 4d ago

Simple answer: that code is wrong as well.

1

u/Purple4cloud7 4d 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 4d ago

Which authorizer?

1

u/KidTempo 4d ago

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

15

u/PeaAble4127 4d 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.

2

u/Fred776 4d ago

So does the other code that op posted

2

u/seanv507 4d 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

0

u/quietcov3 4d ago

spot on, saving the roll to a variable first makes the logic so much easier to read too

0

u/quietcov3 3d ago

That's the exact issue, rolling a second time completely throws off the cumulative math

6

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 4d 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()

4

u/RagingGods 4d 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.

2

u/RagingGods 4d 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".

4

u/igotshadowbaned 4d ago

Or calling random.random once and setting it to a variable

1

u/RagingGods 4d ago

That’s true, but there’s nothing wrong with calling it multiple times as per the question requirements. I omitted that because everyone here has already recommended it. So, I just gave the fastest fix for his code by changing the 9 in his cats variable to 5.

0

u/scoberry5 3d ago

>there’s nothing wrong with calling it multiple times

Wellllll...

If you mean it fulfills the requirements, I agree.

If you mean it will be easy to change if they say "Oh, I changed my mind: I want 'dogs' to be 75% instead of 80%, and 'mouse' the other 5%", then you're wrong: the method you suggested is lots worse.

A better solution than either the original or what you said is to use the numbers they provided: dogs at 80%, cats at 10%, bats at 10%. It can be super clear.

The "correct" method also has the advantage of being more readable: you can see the requirements clearly in the code instead of having to guess how the requirements were mapped to the code.

1

u/RagingGods 3d ago

Idk what do you mean by “You’re wrong”. The question is as direct as it gets. I understand making code maintainable and clean is great practice in production systems, but this is just a probability question one and done with. Injecting a hypothetical situation that doesn’t exist isn’t really proving a working solution “wrong”. Heck, even if I entertain this logic, “if” the question changes to “actually, let me rephrase the question such that dogs are still at 80%, but cats shall be 70% of the other times”, then his code is much easier to change.

Like I said, I’m not discrediting the solutions spammed by a dozen other comments here. OP saw a different valid perspective towards solving a real question (not ifs) and I guided him in that direction, not invalidating and insisting on one “correct” way. In programming there’s no one “correct” method. You can argue maintainability, readability, blah blah textbook answers, I’ll just say mine is faster in fixing the error, getting the actual question correct faster (again, not imaginary scenarios), while demonstrating a deeper understanding of probability by applying conditional probability.

I really don’t need people coming to tell me a proven solution to solve a problem is “wrong”, and then quote irrelevant metrics like maintainability for one-time use leetcode-style codes. We’re here to learn, not invalidate alternatives and insisting on one correct way. I’ve already said I recognise and acknowledge solutions everyone has shared here, I’m not sure if you can say the same.

1

u/scoberry5 3d ago

>Idk what do you mean by “You’re wrong”

Well, I quoted you as saying there's nothing wrong with calling it [random] multiple times. Doing that makes the code more difficult to maintain, but fulfills the requirements. The comment I made differentiated between the two. I'm not sure what I can do to take you from "Idk what do you mean by “You’re wrong”" to "Oh, yeah, you're right: it would work fine, but be less maintainable."

In play-land where you have throwaway code, this doesn't matter much. In real code that sits around for years and that other people have to read, it's better to make the code more readable.

3

u/pdpi 4d 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 4d 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.

2

u/TheRNGuy 4d ago

Better call random once, or you won't have correct algorithm.

2

u/aiuniverse-3p3_here 4d 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/zanfar 4d 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/brasticstack 4d ago edited 4d 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.

0

u/GnPDingo 4d 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 4d 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?

1

u/GnPDingo 4d ago

So when you are calling random for each thing they are isolated events. They do not depend on each other for their outcome and that is just chance, not probability.

Think of it like a lab experiment.
you have a dog a cat and a bat on a table. You call in a random volunteer.
You ask this guy if dog is his favorite. he says yes and you correctly move on.
You call in the next guy and he say No to dog. But before you can find out if he likes either of the other 2 you shoo him away and get another random person and ask them if they like cats.
You have no idea what the second guy liked most and if that third person liked dogs most then you never could find out. those checks are wasted because you got no information from it.

Probability is the likely hood of success VS all other outcomes.
You have this part right
<.8/<.9/<1 is accurate to the 80,10,10
while you may run that brick of code 10 times and get 10 prints
You are actually making somewhere between 15-25 checks to get those 10 points of data.
That's a LOT of voided checks and that will HEAVILY skew your results in an unpredictable fashion

as some others have pointed out the github code is in fact wrong.
Did they ask you to use that as an example or did they ask you take that code and try to correct it?

0

u/aiuniverse-3p3_here 4d 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 4d 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😂