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
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?
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:
import random
import copy
class Hat:
def __init__(self,**kwargs):
self.contents=[]
for attr in kwargs.keys():
self.__dict__[attr] = kwargs [attr]
for i in range (kwargs[attr]):
self.contents.append(attr)
def draw(self,number):
new_contents = copy.copy(self.contents)
extr=[]
if number > len (self.contents):
return new_contents
else:
for i in range (number):
extr.append(random.choice(new_contents))
new_contents.remove(random.choice(new_contents))
return extr