Tell us what’s happening:
Could someone please help me understand what is wrong with this code. It returns a percentage how the test cases want it, yet 2-4 still fail. Someone please help. Thank you.
Your code so far
import copy
import random
class Hat:
def __init__(self, **kwargs):
self.colors = dict(kwargs.items())
self.contents = [ball for ball, count in self.colors.items() for _ in range(count)]
def draw(self, amount):
drawn = []
copied_list = self.contents.copy()
if amount >= len(copied_list):
while self.contents:
ball = random.choice(copied_list)
copied_list.remove(ball)
drawn.append(ball)
else:
for _ in range(amount):
ball = random.choice(copied_list)
copied_list.remove(ball)
drawn.append(ball)
# print(f"-->{self.contents}")
# print(f"^^^{copied_list}")
return drawn
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
times_found = 0
for i in range(num_experiments):
drawn_balls = {}
balls = [ball for ball in hat.draw(num_balls_drawn)]
for ball in balls:#Add balls to drawn_balls
if not ball in drawn_balls:
drawn_balls[f"{ball}"] = 1#Creates new key in dict if not exists
else:
drawn_balls[f"{ball}"] += 1#Increments value if key exists
found = True
for key in expected_balls.keys():#loop through expected balls keys
if key in drawn_balls.keys():#check if expected key is in drawn ball
if drawn_balls[key] >= expected_balls[key]:
continue
else:
found = False
if found:
times_found += 1
percentage = times_found / num_experiments
return f"{percentage:.3f}"
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(probability)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0
Challenge Information:
Build a Probability Calculator Project - Build a Probability Calculator Project