-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbayes.py
71 lines (53 loc) · 1.89 KB
/
bayes.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
67
68
69
70
71
class Die:
def __init__(self, diegen):
self.numdict = {}
for i in diegen:
self.numdict[i] = self.numdict.get(i, 0) + 1
self.chncs = {}
for k in self.numdict.iterkeys():
self.chncs[k] = self.numdict[k] / (len(diegen) * 1.0)
def c(self, num):
return self.chncs.get(num, 0)
def __str__(self):
rounded = map(lambda a: (a[0],round(a[1],3)),self.chncs.items())
return 'Die' + str(rounded)
#@param die_chance: dict, die as key, number of occur in set as val
def bayes_dice(die_chance, rolled):
chance_on_die = {}
for die in die_chance:
chance_on_die[die] = reduce(lambda prod, r: prod * die.c(r), rolled, 1)
chance_of_die = {}
alloccurs = float(sum(die_chance.values()))
for die, occurs in die_chance.iteritems():
chance_of_die[die] = occurs / alloccurs
mults_on_of = { die : chance_on_die[die] * chance_of_die[die] for die in die_chance}
rolled_by_die = {die : mults_on_of[die] / sum(mults_on_of.values()) for die in die_chance}
return rolled_by_die
if __name__ == '__main__':
# rolled = [1, 3, 4, 5, 1, 4, 6, 5, 1, 5, 4, 5]
# d1 = Die(range(1, 7))
# d2 = Die([1, 2, 3, 4, 5, 6, 6])
# d3 = Die([1, 5, 3, 4, 5, 6])
# d4 = Die([1, 5, 3, 4, 5, 5])
#
# d_chcs = {d1:1,
# d2:1,
# d3:1,
# d4:1}
#
# by_die = bayes_dice(d_chcs, rolled)
# for die,chc in by_die.iteritems():
# print die, round(chc,3)
BLACK = 2
WHITE = 1
rolled = [WHITE]*3 + [BLACK]*7
dies = []
for i in range(0,7):
dies.append(Die(i*[BLACK]+(6-i)*[WHITE]))
dchcs = {}
for i in dies:
dchcs[i] = 1
by_die = bayes_dice(dchcs, rolled)
print '------------'
for die,chc in by_die.iteritems():
print die, round(chc,3)