-
Notifications
You must be signed in to change notification settings - Fork 0
/
prob_calculator.py
66 lines (57 loc) · 1.89 KB
/
prob_calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Probability Calculator by Sofia Zavala
04/14/2021
"""
import random
import copy
class Hat:
def __init__(self, **kwargs):
""" Define the sample space.
Keyword args:
keys -- types of balls
values -- quantity of each type
"""
self.contents = [key for key, value in kwargs.items()
for x in range(value)]
def draw(self, num: int):
"""
Pick a ball at (pseudo)random from contents num times, w/o replacement.
Return a list of strings of the type of balls picked.
"""
if num >= len(self.contents): return self.contents
rec = []
for trial in range(num):
ball = random.choice(self.contents)
# Select a random ball.
rec.append(ball)
self.contents.remove(ball)
# Remove the picked ball from contents.
return rec
def experiment(hat, expected_balls: dict, num_balls_drawn: int,
num_experiments: int):
"""
Simulate an experiment of drawing a combination of balls from a hat.
Args:
hat -- a Hat object
expected_balls -- a dict with keys of ball colors and
values of expected number of draws eg. {'red': 2, 'blue': 3}
num_balls_drawn -- number of balls drawn for each experiment
num_experiements -- number of trials
Returns the probability of the drawing a certain combination.
"""
def compare(expect, result):
copy = result[:]
for item in expect:
if item in copy:
copy.remove(item)
return True if not copy else False
event = Hat(**expected_balls)
success = 0
for num in range(num_experiments):
cp = copy.deepcopy(hat)
res = cp.draw(num_balls_drawn)
if compare(event.contents, res):
success += 1
else: continue
prob = success / num_experiments
return prob