Failing tests on probability calculator project

Tell us what’s happening:
My probability number is inaccurate and due to how my draw() function works I fail the test on removing items from list despite it actually working (I use a temp list to remove items not self.contents). I dont know how to fix either of these issues

Your code so far

import copy
import random
from collections import Counter
# Consider using the modules imported above.

class Hat:
def __init__(self,**kwargs):
 self.__dict__.update(kwargs)
 contents=[]
 for key in self.__dict__:
   for x in range(self.__dict__.get(key)):
     contents.append(key)
 self.contents= copy.deepcopy(contents)

def draw(self,num_balls_drawn):
 randomlist = []
 templist = self.contents[:]
 if num_balls_drawn <= len(templist):
   for x in range(num_balls_drawn):
     popped = templist.pop(random.randint(0, len(templist)-1))
     randomlist.append(popped)
   return randomlist 

 else:
   return self.contents
 
 
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
matches = 0
for x in range(num_experiments):
 timesfound = Counter(hat.draw(num_balls_drawn))
 result = ""
 for keys in expected_balls:
   if timesfound[keys] >= expected_balls[keys]:
     pass
   else:
     result = "wrong"
 if result != "wrong":
   matches+=1
return matches/num_experiments


Your browser information:

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

Challenge: Probability Calculator

Link to the challenge:

Welcome to the forums @FreddieBloom.

It looks like all your problems are in your draw function. The test for the draw function is designed to fail if you implement draw() in the way you have with a temporary list. So, implement draw() to pass the tests and don’t use the temporary list.

Since you probably used a temporary list to avoid redraw problems, you might not have considered this hinted at solution: copy the hat every time you need to do a new experiment.

I made these two changes and all tests passed. Good luck.

1 Like

Jeremy,

I removed the temp variable so my draw looked like this:

def draw(self,num_balls_drawn):
    randomlist = []
    if num_balls_drawn <= len(self.contents):
      for x in range(num_balls_drawn):
        popped = self.contents.pop(random.randint(0, len(self.contents)-1))
        randomlist.append(popped)
      return randomlist 

    else:
      return self.contents

And I changed a line in experiment() to

timesfound = Counter(copy.deepcopy(hat).draw(num_balls_drawn))

I believe this now works, was this what you wanted me to do?