Tell us what’s happening:
Hi all,
I’ve already finished my program and I’m getting a very close probability as in the example, but I’m not getting the “check” in the 4th test.
I’m sure my code could be improved, but anyone knows why I don’t get the 4th test?
Thanks!
Your code so far
import copy
import random
class Hat:
pass
def __init__ (self,**kwargs):
if len(kwargs) == 0:
return NotImplemented
self.contents = []
for key, value in kwargs.items():
for _ in range(value):
self.contents.append(key)
if len(self.contents) == 0:
return NotImplemented
def draw(self,num_balls):
balls_list = []
if num_balls >= len(self.contents):
balls_list = list(self.contents)
self.contents.clear()
return balls_list
else:
for _ in range(num_balls):
ball = random.choice(self.contents)
balls_list.append(ball)
self.contents.remove(ball)
return balls_list
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
m = 0
expected_balls_list = []
for key in expected_balls.keys():
for value in range(expected_balls.get(key)):
expected_balls_list.append(key)
#print('Expected_balls_list:',expected_balls_list)
for _ in range(num_experiments):
copia_hat = copy.deepcopy(hat)
tmp = copia_hat.draw(num_balls_drawn)
#print('tmp_ini:',tmp)
for item in expected_balls_list:
if item in tmp:
tmp.remove(item)
#print('tmp_fin:',tmp)
if len(tmp)+len(expected_balls_list) == num_balls_drawn:
m += 1
return m / num_experiments
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
Challenge Information:
Build a Probability Calculator Project - Build a Probability Calculator Project