Probability calculator - copy method

Tell us what’s happening:

Hello! I’m working on the Probability Calculator Challenge for Scientific Computing with Python and I’m having trouble with the test_prob_experiment test function.
I’ve read something about using the copy method and use a copy of the hat for the experiment function in other posts, but I really don’t understand why I have to do that. Can someone explain that to me? Although I don’t know if that’s the only problem that makes my code fail. I would appreciate some help!

Your code so far

import copy
import random
from collections import Counter

class Hat:

    def __init__(self, **kwargs):
        self.contents = []

        for k in kwargs.keys():
            for v in range(0,kwargs.get(k)):

    def draw(self,amount):
        pulled_balls = []
        if amount > len(self.contents):
            #print("The number of balls to draw exceeds the available quantity, returning all the balls")
            for i in range(0,amount):
                contentslength = len(self.contents)
                randomnumber = random.randint(0,contentslength -1) #-1 to preven out of range
        return pulled_balls

def experiment(hat,expected_balls,num_balls_drawn,num_experiments):

    M = 0 #how many times we get expected
    N = 0 #amount of experiments performed
    experiments = num_experiments
    for e in range(experiments):
        taken_balls = hat.draw(num_balls_drawn)
        extracted = Counter(taken_balls) #convert to dict format
        contains_all = True

        #if Extracted contains Expected, M += 1
        for k,v in expected_balls.items():
            if k in extracted.keys() and extracted.get(k) >= expected_balls.get(k):
                contains_all = True
                contains_all = False
        if contains_all == True:
                M += 1
        N += 1

    probability = M/N
    return probability
    #print("Probability: ",probability)

#hat = Hat(blue=3,red=2,green=6)
#experiment(hat=hat, expected_balls={"blue":2,"green":1}, num_balls_drawn=4, num_experiments=1000)
#expected probability 0.272

The console


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.

Challenge: Probability Calculator

Link to the challenge:

Your propability is basically zero - so basically your expirement doesn’t return the right amount of balls ever.

If I see it correctly, I think you just never resett your hat. In practical terms: You never return the balls you drew. Your hat is empty after the second of 1000 experiments.

1 Like

Thank you! I was just thinking about that, because of the strange amount of “successful matches” that was returning in the M variable! That was it, thank you very much!