Probability Calculation and draw only working outside of tests

Challenge: Probability Calculator


My code for the Probability Calculator ( works well outside of the testing suite. I can get the correct draw and probability when I replicate the testing conditions in However the two tests test_hat_draw and test_prob_experiment fail whenever I run the tests.

I am wondering if it is something to do with how I am doing my draws, specifically. Could someone take a look and let me know if there are any glaring issues with this code block? If not, I will delete this and post my experiment snip instead.

Existing code:

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

Could you show the rest of your code (not as an image) or link to it on replit?

1 Like

Sure, here is the link:

Issue is with the way hat contents and og_contents are kept. Because those are defined as a class variables, and the latter one is not emptied during instantiation of new hat, the balls from one test can make to next one. This results in different, than expected, balls existing in hat on the start of test.

Usually it’s best to avoid using class variables, unless it’s absolutely necessary, in favor of instance variables (defined as self.x in __init__). This limits the risk of unexpected side-effects.


Thanks so much for taking a look! I was able to get it fixed up to pass the tests, and your explanation makes sense. I believed I was using instance variables by calling self.contents, but I’m assuming it counts as a class variable as well given my declaration at the top of the class?

Kind of, python first searched among instance variables, and as didn’t find those variables there, then searched class variables.

1 Like

Sorry if I re-open this thread but I feel like I have a very similar problem and I probably didn’t understand the root cause or the explanation. Below my code (the first part), the method ‘draw’ returns correctly random colors when I test in but always return [‘blue’, blue’] when I run the actual test. What am I doing wrong? Thank you:

import random
import copy
class Hat:

    def __init__(self,**kwargs):

        for attr in kwargs.keys():
            self.__dict__[attr] = kwargs [attr]
            for i in range (kwargs[attr]):

    def draw(self,number):
        new_contents = copy.copy(self.contents)
        if number > len (self.contents):
            return new_contents
            for i in range (number):
            return extr