Build a Probability Calculator Project - Failing on test 4

Tell us what’s happening:

I made a code that i think works fine, but fails the last test “Expected experiment method to return a different probability.” Could you help me find out what couses this problem?
Here is a picturo of my console:

Your code so far

import copy
import random

class Hat:
    def __init__(self, **contents):
        self.contents = [colour for colour, amount in contents.items() for _ in range(amount)]

    def draw(self, num):
        if num > len(self.contents):
            drawn_balls = self.contents
            self.contents = []
            return drawn_balls
        drawn_balls = []
        for _ in range(num):
            ball = (random.choice(self.contents))
            drawn_balls.append(ball)
            self.contents.remove(ball)
        return drawn_balls

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    successes = 0
    for _ in range(num_experiments):
        hat_copy = Hat(**{color: hat.contents.count(color) for color in set(hat.contents)})
        drawn_balls = hat_copy.draw(num_balls_drawn)
        drawn_counts = {ball: drawn_balls.count(ball) for ball in drawn_balls}
        if all(drawn_counts.get(colour, 0) >= balls for colour, balls in expected_balls.items()):
            successes += 1
    return successes/num_experiments


hat = Hat(black=6, red=4, green=3)
probability = experiment(hat=hat,
                  expected_balls={'red':2,'green':1},
                  num_balls_drawn=5,
                  num_experiments=2000)
print(probability)






Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36

Challenge Information:

Build a Probability Calculator Project - Build a Probability Calculator Project

you may need to try other random methods to see if it returns a different priobability

1 Like

Okay i used the secrets package instead of random, I only changed
ball = (random.choice(self.contents))
this line to
ball = (secrets.choice(self.contents))
Now the test 4 is successful, but test 2 is wrong. Any idea why?

If a hat has 5 balls and you draw 1, then the contents of the hat would now be 4 balls, right?

Thank you for the answers, i dont know what happened, i kept running the tests again and again then it accepted all of them.

if your app doesn’t reliably pass the tests maybe there are some issues

also you should still use the random package, but try different methods