Tell us what’s happening:
I get the following error (the ‘draw’ method should behave correctly when the number of balls to extract is bigger than the number of balls in the hat).
I currently return the required, I have also tried the .copy() function from the import, but the third error is still there
Your code so far
import copy
import random
class Hat:
def __init__(self, **hats):
self.contents = []
for key, val in hats.items():
for i in range(val):
self.contents.append(key)
#print(self.contents)
def draw(self, num):
if num >= len(self.contents):
return self.contents
else:
drawnlist = []
for i in range(num):
drawn = random.sample(self.contents, 1)
drawnlist += drawn
for ball in drawn:
if ball in self.contents:
self.contents.remove(ball)
#print(drawn)
#print(drawnlist)
return drawnlist
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
count = 0
for experiment in range(num_experiments):
expectedlist = []
for color, num in expected_balls.items():
for j in range(num):
expectedlist.append(color)
#print(expectedlist)
newhat = copy.deepcopy(hat)
samplelist = newhat.draw(num_balls_drawn)
for color in samplelist:
if color in expectedlist:
expectedlist.remove(color)
if len(expectedlist) == 0:
count += 1
probability = count / num_experiments
#print(probability)
return probability
hat = Hat(black=6, red=4, green=3)
hat.draw(3)
probability = experiment(hat=hat,
expected_balls={'red':2,'green':1},
num_balls_drawn=5,
num_experiments=2000)
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15
Challenge Information:
Build a Probability Calculator Project - Build a Probability Calculator Project