import copy
import random
from collections import Counter
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.contents = []
for k, v in kwargs.items():
self.contents += v * [k]
def draw(self, num):
new_list= []
if num > len(self.contents):
return self.contents
else:
for i in range(num):
element = self.contents.pop(int(random.random() * len(self.contents)))
new_list.append(element)
return new_list
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
probability = 0.0
favourable_outcome = 0
ex_list = []
for k, v in expected_balls.items():
ex_list += v * [k]
for i in range(num_experiments):
outcome = copy.deepcopy(hat)
new_outcome = outcome.draw(num_balls_drawn)
su_nu = []
#dict1 = Counter(ex_list)
#dict2 = Counter(new_outcome)
#print(dict2)
#if dict1 == dict2:
#favourable_outcome +=1
equal = True
for i in ex_list:
if i in new_outcome:
el = new_outcome.pop(new_outcome.index(i))
su_nu.append(el)
else:
equal = False
break
if equal:
favourable_outcome+=1
#dict1 = Counter(ex_list)
#ict2 = Counter(su_nu)
#if dict1 == dict2:
# favourable_outcome +=1
probability = favourable_outcome/num_experiments
return probability
I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.