Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/monty.py
1901 views
1
"""This file contains code for use with "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
from thinkbayes2 import Pmf
11
12
13
class Monty(Pmf):
14
"""Map from string location of car to probability"""
15
16
def __init__(self, hypos):
17
"""Initialize the distribution.
18
19
hypos: sequence of hypotheses
20
"""
21
Pmf.__init__(self)
22
for hypo in hypos:
23
self.Set(hypo, 1)
24
self.Normalize()
25
26
def Update(self, data):
27
"""Updates each hypothesis based on the data.
28
29
data: any representation of the data
30
"""
31
for hypo in self.Values():
32
like = self.Likelihood(data, hypo)
33
self.Mult(hypo, like)
34
self.Normalize()
35
36
def Likelihood(self, data, hypo):
37
"""Compute the likelihood of the data under the hypothesis.
38
39
hypo: string name of the door where the prize is
40
data: string name of the door Monty opened
41
"""
42
if hypo == data:
43
return 0
44
elif hypo == 'A':
45
return 0.5
46
else:
47
return 1
48
49
50
def main():
51
hypos = 'ABC'
52
pmf = Monty(hypos)
53
54
data = 'B'
55
pmf.Update(data)
56
57
for hypo, prob in sorted(pmf.Items()):
58
print(hypo, prob)
59
60
61
if __name__ == '__main__':
62
main()
63
64