Tell us what’s happening:
Hi all, I’ve spent over a day trying to troubleshoot why it doesn’t pass test 3 and 4. Would love any feedback you can give me to help point me to the right direction.
My draw() seems to return the same list when the draw number exceeds the number of balls available, and the experiment() seems to match the right pattern of balls and account for it in variable M… The codes is not super pretty but it usually helps me out to right out the whole codes instead of in list comprehension. Thanks!
Your code so far
import copy
import random
class Hat:
def __init__(self, **kwargs):
self.contents = [ball for ball in kwargs for _ in range(kwargs[ball])]
def draw(self, number):
total = len(self.contents)
draw_list = []
if number > total:
draw_list = self.contents
else:
for _ in range(number):
random_num = random.randint(0, total-1)
draw_list.append(self.contents.pop(random_num))
total -= 1
return draw_list
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
expected_list = []
for ball in expected_balls:
for _ in range(expected_balls[ball]):
expected_list.append(ball)
M = 0
for _ in range(num_experiments):
match = []
new_hat = copy.deepcopy(hat)
new_expected_list = copy.deepcopy(expected_list)
drawn = new_hat.draw(num_balls_drawn)
for ball in drawn:
if ball in new_expected_list:
match.append(ball)
new_expected_list.remove(ball)
if sorted(match) == sorted(expected_list):
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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Safari/605.1.15
Challenge Information:
Build a Probability Calculator Project - Build a Probability Calculator Project