hello everyone, I am almost finished with the probability calculator, and am a bit lost on the deepcopy method in the copy module. Here is my problem: this is the code for my experiment function:
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
""" a function that returns the probability of drawing certain colours of balls out of
the hat over n experiments"""
match = 0
expected_balls_set = set(expected_balls.keys())
for i in range(num_experiments):
copied_hat = copy.deepcopy(hat)
balls_drawn_in_experiment = copied_hat.draw(num_balls_drawn)
balls_drawn_in_experiment_set = set(balls_drawn_in_experiment)
for i in range(num_experiments):
if set(balls_drawn_in_experiment_set).intersection(set(expected_balls_set)) != 0:
match = + 1
probability = match / num_experiments
return probability
Which creates a copy of the hat, and then creates a set of the copied hat, with which the intersection method is used to see if the expected balls match the balls that were drawn. I have checked various forums and the python copy module documentation and all sources seem to point to the idea that sets can be copied and deepcopied. But when I try this code out, I fail the third test, as it says that the probability I gave was incorrect *( 00.1 != 0.272)
I have found a snippet of code written by another user for the probability experiment that in both structure and syntax is very similar to mine, except it does not use sets, and when I tried and substitute that piece of code in my program the calculator passed all tests
Here is the user’s code:
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
favourable_outcomes = 0
for _ in range(num_experiments):
isFavourable = True
experiment_hat = copy.deepcopy(hat)
balls_drawn = experiment_hat.draw(num_balls_drawn)
# count the number of balls from balls_drawn with the expected_balls; If they are equal to the expected balls, increment
# favourable outcomes.
for ball_color,count in expected_balls.items():
if isFavourable:
if balls_drawn.count(ball_color) >= count:
isFavourable = True
else:
isFavourable = False
if isFavourable:
favourable_outcomes += 1
return favourable_outcomes/num_experiments
Any ideas of why their code which doesn’t use sets work? I know I can come up with a similar function that also doesn’t use sets that will be able to pass the tests, but at this point more than having a hint towards a solution I am just curious about the reason why sets don’t seem to work as a solution to the problem.
Many thanks to you all!