Challenge: Probability Calculator
My code for the Probability Calculator (https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/probability-calculator) works well outside of the testing suite. I can get the correct draw and probability when I replicate the testing conditions in main.py. 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.
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?
Issue is with the way hat
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
__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.
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 main.py but always return [‘blue’, blue’] when I run the actual test. What am I doing wrong? Thank you:
for attr in kwargs.keys():
self.__dict__[attr] = kwargs [attr]
for i in range (kwargs[attr]):
new_contents = copy.copy(self.contents)
if number > len (self.contents):
for i in range (number):
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.