Scientific Computing with Python Projects - Probability Calculator

Tell us what’s happening:

Describe your issue in detail here.

Your code so far

import random

class Hat:
    def __init__(self, **balls):
        self.contents = []
        for color, count in balls.items():
            self.contents += [color] * count

    def draw(self, num_balls):
        drawn_balls = random.sample(self.contents, min(num_balls, len(self.contents)))
        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 = Hat(**hat.contents)
        drawn_balls = hat_copy.draw(num_balls_drawn)
        
        # Check if all expected balls are drawn
        success = True
        for color, count in expected_balls.items():
            if drawn_balls.count(color) < count:
                success = False
                break
        
        if success:
            success_count += 1
    
    return success_count / num_experiments

# Example usage
hat = Hat(blue=5, red=4, green=2)
probability = experiment(hat=hat,
                         expected_balls={"red": 1, "green": 2},
                         num_balls_drawn=4,
                         num_experiments=10000)
print("Probability:", probability)

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15

Challenge Information:

Scientific Computing with Python Projects - Probability Calculator

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

the code is not working and I’m totally confused

Please talk to us about how the instructions or error message is confusing. Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.