Build a Probability Calculator Project - Build a Probability Calculator Project

Tell us what’s happening:

Not sure why my draw function won’t pass the test of when the number of balls to extract is bigger than the number of balls in the hat.

Your code so far

import copy
import random


class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for ball in kwargs.items():
            for i in range(0, ball[1]):
                self.contents.append(ball[0])

    def draw(self, number_of_balls_drawn):
        if number_of_balls_drawn > len(self.contents):
            return self.contents

        balls_drawn = []
        for i in range(0, number_of_balls_drawn):
            random_ball = random.choice(self.contents)
            balls_drawn.append(random_ball)
            self.contents.remove(random_ball)

        return balls_drawn


def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    success = 0
    for i in range(0, num_experiments):
        test = copy.deepcopy(hat)
        balls = test.draw(num_balls_drawn)
        counts = {}
        match = True
        for ball in balls:
            counts[ball] = counts.get(ball, 0) + 1
        for color in expected_balls:
            if counts.get(color, 0) < expected_balls[color]:
                match = False
        if match:
            success = success + 1
    return success / num_experiments

hat = Hat(black=6, red=4, green=3)
print(hat.draw(14))


Your browser information:

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

Challenge Information:

Build a Probability Calculator Project - Build a Probability Calculator Project

If you withdraw all of the balls from the hat, how many balls remain in self.contents ?

Does it not return all of the balls that were originally put into the hat? Isn’t that what it is supposed to do?

you need to return the balls, and empty the hat. Like if you extract three balls the tests check if there are 3 balls less in the hat, if you extract all of them, it checks if the hat is empty

Keep in mind that returning the balls and removing them from the hat are two separate operations.

1 Like

Thanks for the help! I ended up saving them to a temporary variable, then clearing the list, then returning the temporary variable of all the balls.

1 Like