Hi I have a problem with my random module in the probability calculator. I tried to debug and it is not generating a random number.
import random
import copy
random.seed(2)
class Hat:
def __init__(self, **kwargs):
self.items = kwargs
self.contents = []
self.drawed_balls = []
self.drawed_balls2 = []
for ball, number in self.items.items():
for i in range(number):
self.contents.append(ball)
self.duplicate = copy.copy(self.contents)
def draw(self, times_drawn):
if times_drawn <= len(self.contents):
for i in range(times_drawn):
random_index= random.randint(0, len(self.contents)-1)
self.drawed_balls.append(self.contents[random_index])
self.contents.pop(random_index)
self.contents = self.duplicate
else: pass
return self.drawed_balls
def clear(self):
self.drawed_balls = self.drawed_balls2
def __repr__(self):
return self.items
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
hat = hat
expected_ball = []
for ball, number in expected_balls.items():
for i in range(number):
expected_ball.append(ball)
ball_drawn = num_balls_drawn
experiments = num_experiments
passed = 0
for i in range(experiments):
if expected_ball in hat.draw(ball_drawn):
hat.clear()
passed += 1
else: pass
return passed/experiments
It just picks a certain number in the randint range and it will remain that way for the rest of the experiment. I am checking in Thonny and that’s what it shows. The probability always is 0
This isn’t a problem with the random module. This is a problem with your code. Prematurely identifying a root cause limits your debugging and can lead you to waste time on things that aren’t the issue.
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
hat = hat
expected_ball = []
for ball, number in expected_balls.items():
for i in range(number):
expected_ball.append(ball)
ball_drawn = num_balls_drawn
experiments = num_experiments
passed = 0
for i in range(experiments):
if expected_ball in hat.draw(ball_drawn):
hat.clear()
passed += 1
else: pass
return passed/experiments
This here is part of the problem. This code doesn’t run num_experiments draws and check if they contain the expected balls.
Also, you need to run the experiment on a fresh copy of the hat each time. You are emptying the same hat out, so it has nothing left in it to draw.
A hat object containing balls that should be copied inside the function.