-
-
Save prophile/9aacbc41cfa05b4cccb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def roll(dice=1): | |
import random | |
return sum(random.randint(1, 6) for i in xrange(dice)) | |
class CrapsGame: | |
def __init__(self): | |
self.outcome = None | |
self.point = None | |
self.rolls = [] | |
def step(self, roll): | |
if self.point is None: | |
if roll in (2, 3, 12): | |
self.outcome = "loss" | |
elif roll in (7, 11): | |
self.outcome = "win" | |
else: | |
self.point = roll | |
else: | |
if roll == 7: | |
self.outcome = "lose" | |
elif roll == self.point: | |
self.outcome = "win" | |
self.rolls.append(roll) | |
@classmethod | |
def complete_game(self): | |
instance = self() | |
while instance.outcome is None: | |
instance.step(roll(dice=2)) | |
return instance | |
def mean(dataset): | |
total = dataset.next() | |
count = 1 | |
for value in dataset: | |
total += value | |
count += 1 | |
return total / float(count) | |
def fraction(test, dataset): | |
count = 0 | |
matched = 0 | |
for value in dataset: | |
count += 1 | |
matched += 1 if test(value) else 0 | |
return float(matched) / float(count) | |
games = [CrapsGame.complete_game() for i in xrange(100000)] | |
print "Win rate: ", fraction(lambda x: x.outcome == "win", games) | |
print "Average roll count: ", mean(len(x.rolls) for x in games) | |
print "Average roll: ", mean(roll for x in games for roll in x.rolls) | |
print "Maximum roll count: ", max(len(x.rolls) for x in games) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment