Created
January 16, 2024 23:27
-
-
Save berdfandrade/1a8c34f5aec7b351d5e3db00121b5d6d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
import random | |
class Hat: | |
def __init__(self, **balls): | |
self.contents = [] | |
for color, count in balls.items(): | |
self.contents.extend([color] * count) | |
def draw(self, num_balls): | |
drawn_balls = [] | |
if num_balls >= len(self.contents): | |
return self.contents | |
for _ in range(num_balls): | |
ball = random.choice(self.contents) | |
self.contents.remove(ball) | |
drawn_balls.append(ball) | |
return drawn_balls | |
def experiment(hat, expected_balls, num_balls_drawn, num_experiments): | |
successful_experiments = 0 | |
for _ in range(num_experiments): | |
hat_copy = copy.deepcopy(hat) | |
drawn_balls = hat_copy.draw(num_balls_drawn) | |
drawn_balls_dict = {} | |
for ball in drawn_balls: | |
drawn_balls_dict[ball] = drawn_balls_dict.get(ball, 0) + 1 | |
success = True | |
for color, count in expected_balls.items(): | |
if drawn_balls_dict.get(color, 0) < count: | |
success = False | |
break | |
if success: | |
successful_experiments += 1 | |
probability = successful_experiments / num_experiments | |
return probability |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment