Build a Probability Calculator Project - Build a Probability Calculator Project

Tell us what’s happening:

Hi all,
I’ve already finished my program and I’m getting a very close probability as in the example, but I’m not getting the “check” in the 4th test.
I’m sure my code could be improved, but anyone knows why I don’t get the 4th test?

Thanks!

Your code so far

import copy
import random

class Hat:
    pass

    def __init__ (self,**kwargs):
        if len(kwargs) == 0:
            return NotImplemented
        self.contents = []
        for key, value in kwargs.items():
            for _ in range(value):
                self.contents.append(key) 
        if len(self.contents) == 0:
            return NotImplemented

    def draw(self,num_balls):
        balls_list = []
        if num_balls >= len(self.contents):
            balls_list = list(self.contents)
            self.contents.clear()
            return balls_list
        else:
            for _ in range(num_balls):
                ball = random.choice(self.contents)
                balls_list.append(ball)
                self.contents.remove(ball)
        return balls_list

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    m = 0
    expected_balls_list = []
    for key in expected_balls.keys():
        for value in range(expected_balls.get(key)):
            expected_balls_list.append(key)
    #print('Expected_balls_list:',expected_balls_list)  
    for _ in range(num_experiments):
        copia_hat = copy.deepcopy(hat)
        tmp = copia_hat.draw(num_balls_drawn)
        #print('tmp_ini:',tmp)
        for item in expected_balls_list:
            if item in tmp:
                tmp.remove(item)
        #print('tmp_fin:',tmp)
        if len(tmp)+len(expected_balls_list) == num_balls_drawn:
            m += 1 
    return m / 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

looking at the browser console I see

AssertionError: 0.0 != 1.0 within 0.01 delta (1.0 difference) : Expected experiment method to return a different probability.

your function output is 0.0 for whatever case should be 1.0

the test that is failing is calling

hat = Hat(yellow=5,red=1,green=3,blue=9,test=1)
probability = experiment(hat=hat, expected_balls={"yellow":2,"blue":3,"test":1}, num_balls_drawn=20, num_experiments=100)

try to figure out where the function goes wrong

Ok, I didn’t know about the “browser console” thing. I’ll take a look to see what’s wrong.

Thank you for the hint!