Build a Probability Calculator Project - Build a Probability Calculator Project

Tell us what’s happening:

I’m a bit stuck when told my Draw method needs to return the original list if greater than the number of balls in my code fails but this is what I have:

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

I’m I just missing something or is this possibly a bug?

Your code so far

import random
from copy import deepcopy
class Hat:
    def __init__(self, **balls):
        self.contents = []
        for color, count in balls.items():
            self.contents.extend([color] * count)
   
#  ↓ This is the line    ↓ 
 def draw(self, num_balls):
        if num_balls > len(self.contents):
            return self.contents
    

        drawn_balls = random.sample(self.contents, num_balls)
        for ball in drawn_balls:
            self.contents.remove(ball)
        
        return drawn_balls


def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    success_count = 0


    for _ in range(num_experiments):
        hat_copy = deepcopy(hat)
        drawn_balls = hat_copy.draw(num_balls_drawn)
        drawn_count = {}
        for ball in drawn_balls:
            if ball in drawn_count:
                drawn_count[ball] += 1
            else:
                drawn_count[ball] = 1
        success = True
        for color, count in expected_balls.items():
            if drawn_count.get(color, 0) < count:
                success = False
                break

        if success:
            success_count += 1
    return success_count / num_experiments


if __name__ == "__main__":
    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(f"Probability: {probability}")

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

The hat should be emptied in any case. So returning self.contents is not enough to pass the test.