Skip to content

Instantly share code, notes, and snippets.

@prophile
Created February 28, 2012 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prophile/9aacbc41cfa05b4cccb1 to your computer and use it in GitHub Desktop.
Save prophile/9aacbc41cfa05b4cccb1 to your computer and use it in GitHub Desktop.
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