I almost finished the task but in the experiment function i can’t put list with draw balls inside for loop to get everytime new result. (i got value error)
import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **args):
self.contents = list()
for v,k in args.items():#n-times add color ball
self.contents += k*[v]
def draw(self, num_balls):
if(num_balls > len(self.contents)):
return self.contents
else:
drawballs = list()
for k in range(num_balls):
drawballs.append(self.contents.pop(random.randint(0, len(self.contents)- 1 - k)))
return drawballs
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
expect = list()
balls = copy.deepcopy(hat)
allballs = balls.draw(num_balls_drawn)
for v,k in expected_balls.items():
expect += k * [v]
m = 0
for i in range(num_experiments):
#allballs = balls.draw(num_balls_drawn)
if(all(x in allballs for x in expect)):
m += 1
print(m)
prob = m / num_experiments
return prob
Traceback (most recent call last):
File "main.py", line 6, in <module>
probability = prob_calculator.experiment(
File "/home/runner/boilerplate-probability-calculator/prob_calculator.py", line 33, in experiment
allballs = balls.draw(num_balls_drawn)
File "/home/runner/boilerplate-probability-calculator/prob_calculator.py", line 20, in draw
drawballs.append(self.contents.pop(random.randint(0, len(self.contents)- 1 - k)))
File "/usr/lib/python3.8/random.py", line 248, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.8/random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
exit status 1
Error occurs when variable allballs with ball drawed from the one and only hat object is inside for loop and only when it is there i got every time different set of balls which is right but in if(all(x in allballs for x in expect)):
i got error which lead to random.py code error line
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))```.
And when var out of for loop the is the same so test fails.
The hat is the same (the first argument) but every time you draw balls from it you need to get different results this is why i’m trying to put var allballs inside for loop but error appears
Let me write it differently - error is because after few experiments no ball is left in the hat.
Different result of the draw comes from fact of using random module for drawing balls, not because after each experiment different number of balls is left in hat for next experiment.