Scientific Computing with Python Projects - Probability Calculator

Tell us what’s happening:

Hello, my last test is not passing, even though I get a roughly estimate of the probability when running from same parameters three times. Can I please be assistant because with each experiement I reset my hat contents for consistancy what could I be doing wrong the draw again the expected balls as per param, that part seems to fine to me logically. I also refresh the hat.contents or update it with the copied content (hat_copy) at the end of the for loop. the what could I be doing wrong?

My code thus far!

import copy
import random

class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for color, count in kwargs.items():
    def draw(self, num_balls_drawn):
        sel_ball = ''
        drawn_balls = []
        for num_ball in range(num_balls_drawn):
            sel_ball = random.randrange(len(self.contents))
        return drawn_balls

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    hat_copy = copy.deepcopy(hat.contents)
    M = 0
    N = num_experiments
    for _ in range(N):
        # print(len(hat.contents))
        draw = hat.draw(num_balls_drawn)
        # print(len(hat.contents))
        success = True
        for color, count in expected_balls.items():
            if draw.count(color) < count:
                success = False

        if success:
            M += 1
        hat.contents = copy.deepcopy(hat_copy)
    return M/N

hat = Hat(black=6, red=4, green=3)

probability1 = experiment(hat=hat,

probability2 = experiment(hat=hat,

probability3 = experiment(hat=hat,
print(probability1,probability2, probability3)

The results obtained on the picture.


Your browser information:

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

Challenge Information:

Scientific Computing with Python Projects - Probability Calculator

If you take a look at the browsers’s console, there will be displayed tests results with more details. The issue is from incorrect handling the case when number of balls to draw is higher than the actual number of balls in the hat.

I did not consider that to be the case I though 0 probability was valid for that case. Now that I fixed it , I manage to pass the last test. Thank you.