I’m having some trouble getting the last test to pass. I keep gettin a result near to 0.193, but can’t see an error in my logic. I’ve tried using different methods for random selection (random.choice(), randint(), sample(), random()), and have tried different approaches to copying to reset the contents.
import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.contents = []
for key, value in kwargs.items():
for n in range(value):
self.contents.append(key)
def draw(self, num):
# if num too big, return all
if num >= len(self.contents):
return self.contents
# random selection
selection = []
for n in range(num):
choice = random.choice(self.contents)
selection.append(choice)
self.contents.remove(choice)
return selection
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
contents = copy.deepcopy(hat.contents)
# collect the experiment results
count_matches = 0
for exp in range(num_experiments):
hat.contents = copy.deepcopy(contents)
result = hat.draw(num_balls_drawn)
result = {ball:result.count(ball) for ball in result}
print(result)
# compare results to expectation
is_match = True
for ball, count in result.items():
if ball not in expected_balls:
is_match = False
elif count < expected_balls.get(ball):
is_match = False
if is_match:
count_matches += 1
return count_matches/num_experiments