Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
91 lines (60 sloc) 2.09 KB
import random
# Dice Game
# Problem 205
# Peter has 9, 4-sided dice, each with faces numbered week1, 2, 3, 4.
# Colin has 6, 6-sided dice, each with faces numbered week1, 2, 3, 4, 5, 6.
# Peter and Colin roll their dice and compare totals: the highest total wins.
# The result is a draw if the totals are equal.
# What is the probability that Pyramidal Pete beats Cubic Colin?
# Give your answer rounded to seven decimal places in the form 0.a b c d e f g
# Peter's dice will be referred to as d1 from this point onward and Colin's as d2
rr = random.randint
def make_diesum(s):
a, K, f = s
if type(f) == dict:
f = dic_to_func(f)
K = list(K)
def diesum_():
return sum(random.choices(K, weights=[f(x) for x in K], k=a))
return diesum_
def runexp(s1, s2, n):
diesum1 = make_diesum(s1)
diesum2 = make_diesum(s2)
counter = 0
def onetrial():
return diesum1() > diesum2()
for _ in range(n):
if onetrial():
counter += 1
return counter / n
def report(case_name, s1, s2, n):
print(case_name)
print('The probability that S1 beats S2 is: ', str(runexp(s1, s2, n)) + '\n' + '\n')
def dic_to_func(dic):
def f_(k):
return dic[k] if k in dic else 0
return f_
Case1 = 'Case1'
S1 = (9, {1, 2, 3, 4}, lambda x: 1 / 4)
S2 = (6, {1, 2, 3, 4, 5, 6}, lambda x: 1 / 6)
print(report(Case1, S1, S2, 10000))
Case2 = 'Case2'
S1 = (1, set(range(1, 36 + 1)), lambda x: 1 / 36)
S2 = (36, {0, 1}, lambda x: 1 / 2)
print(report(Case2, S1, S2, 10000))
Case3 = 'Case3'
S1 = (6, {1, 2, 3, 4}, lambda x: 1 / 4)
S2 = (4, {1, 2, 3, 4, 5, 6}, lambda x: 1 / 6)
print(report(Case3, S1, S2, 10000))
Case4 = 'Case4'
S1 = (6, {1, 2, 3, 4}, {1: 1 / 3, 2: 1 / 5, 3: 1 / 7, 4: 1 - 1 / 3 - 1 / 5 - 1 / 7})
S2 = (4, {1, 2, 3, 4, 5, 6}, lambda x: 1 / 6)
print(report(Case4, S1, S2, 10000))
Case5 = 'Case5'
S1 = (55, {1, 3}, lambda x: 1 / 2)
S2 = (20, set(range(1, 11)), lambda x: 1 / 10)
print(report(Case5, S1, S2, 10000))
Case6 = 'Case6'
S1 = (10, {1, 3}, lambda x: 1 / 2)
S2 = (20, {0, 2}, lambda x: 1 / 2)
print(report(Case6, S1, S2, 10000))
You can’t perform that action at this time.