Hello everybody, it’s me again.
I am working on the final assignment and I am a bit stuck on the experiment function. Here’s what the description says
Each experiment consists of starting with a hat containing the specified balls, drawing several balls, and checking if you got the balls you were attempting to draw.
So, each experiments should run a N number of times. I should draw balls from the Hat and compare the result with what I expected. Everytime I get the expected I should add it until the numbers of experiments are complete. Here’s how my code for this part looks:
def experiment (Hat,num_balls_drawn,num_experiments,expected_balls):
for trials in range(num_experiments):
draws = Hat.draw(num_balls=num_balls_drawn)
draws_dict = dict_of_balls(draws)
total_trials = 0
probability_result = 0
for keys in draws_dict:
if expected_balls.keys():
return probability_result
It’s still incomplete, my question is:
How do I compare the draws with what is expected? I was thinking that it would make more sense to compare them as dictionaries, because I could compare if the key was in there but also that the number as well.
This is my code so far:
import copy
import random as rd
def list_of_balls(hat_dict):
'Turns a dictionary into a list, repeating the keys times value'
for keys in hat_dict:
balls_list = []
num_balls = hat_dict[keys]
colour_name = keys
for balls in range(num_balls):
balls_list.append(colour_name)
def dict_of_balls(list):
'Turns a list into a dictionary, keys are the elements and values are the times they are repeated in the list'
final_dict = {}
for balls in list:
ball_number = list.count(balls)
final_dict.update({balls:ball_number})
return final_dict
class Hat:
def __init__(self, hats={}):
self.hats = dict(hats)
# self.content = list(self.hats.keys())
self.content = []
self.total_number_balls = sum(self.hats.values())
self.list_keys = list(self.hats.keys())
for keys in self.hats:
num_balls = self.hats[keys]
colour_name = keys
for balls in range(num_balls):
self.content.append(colour_name)
def draw (self,num_balls):
#_______Remove balls at random from the hat
# random_ball = rd.choice(content_copy)
Total_quantity = self.total_number_balls
content_copy = self.content.copy()
content_copy_length = len(content_copy)
random_balls_list = []
for draws in range(num_balls):
if num_balls > content_copy_length:
return 'Balls returned'
# content_copy.pop(random_ball)
random_balls_list.append(rd.choice(content_copy))
return random_balls_list
def experiment (Hat,num_balls_drawn,num_experiments,expected_balls):
for trials in range(num_experiments):
draws = Hat.draw(num_balls=num_balls_drawn)
draws_dict = dict_of_balls(draws)
total_trials = 0
probability_result = 0
for keys in draws_dict:
if expected_balls.keys():
return probability_result