Tell us what’s happening:
I think I got the correct probability but I don’t know why I could not pass the last test. Is there any error or do I need to use another method?
Your code so far
import copy
import random
class Hat():
def __init__(self, **kwargs):
self.contents=[]
for colour, value in kwargs.items():
for i in range(value):
self.contents.append(colour)
def draw(self,no_of_balls):
ball_drawn=[]
if no_of_balls > len(self.contents):
ball_drawn = list(self.contents)
self.contents.clear()
return ball_drawn
for i in range(no_of_balls):
ball = random.choice(self.contents)
ball_drawn.append(ball)
self.contents.remove(ball)
return ball_drawn
def __str__(self):
return str(self.contents)
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
M=0
N=num_experiments
expected=[]
for colour, value in expected_balls.items():
expected += [colour]*value
for n in range(N):
K = 0
drawn = sorted(hat.draw(num_balls_drawn))
for i in range(num_balls_drawn+1-len(expected)):
if sorted(expected) == drawn[i:i+len(expected)]:
K+=1
if K > 0:
M+=1
hat.contents += drawn
return M/N
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/127.0.0.0 Safari/537.36
Challenge Information:
Build a Probability Calculator Project - Build a Probability Calculator Project