""" craps.py in class Oct 13 looking at craps Jim M et al ... we didn't get this debugged or quite finished, the first part with craps works, but the statistics routines haven't been tested or used with craps yet. """ def d6(): """ Return a random integer from 1 to 6 inclusive. >>> x = d6() >>> int(x) == x True >>> 1 <= x <= 6 True """ from random import randrange return randrange(1,7) def two_d6(): """ Return sum of two six sided dice. """ return d6() + d6() def win_craps(): """Play one game of craps. Return True if you win.""" first_roll = two_d6() # print "first_roll = ", first_roll if first_roll == 2 or first_roll == 3 or first_roll == 12: # print "first roll was 2,3,12" return False elif first_roll == 7 or first_roll == 11: # print "first roll was 7,11" return True else: while True: next_roll = two_d6() # print "next roll is ", next_roll if next_roll == first_roll: # print "point achieved" return True elif next_roll == 7: # print "crapped out" return False def count_games(n): """Play n games of craps. Return number won.""" count = 0 for i in range(n): if win_craps(): count = count + 1 return count def list_of_count_games(n_game, list_size): """Return list of playing n_games rounds of craps.""" answer = [0] * list_size for i in range(list_size): answer[i] = count_games(n_game) return answer def mean(numbers): """Return mean of a list of numbers. >>> mean([1,2,3]) 2.0 """ return float(sum(numbers))/len(numbers) def standard_deviation(numbers): """Return standard deviation of list of numbers. # >>> """ from math import sqrt average = mean(numbers) n = len(numbers) square_diffs = [0] * n for i in range(n): square_diffs[i] = (numbers[i] - average)**2 return sqrt(mean(square_diffs)) def main(): print "--- Estimated odds of winning at craps ---" number_of_games = input("How many games would you like to simulate? (100) ") print "Simulating %i games ..." % number_of_games number_won = count_games(number_of_games) print "done." print "Number of simulated wins : %i" % number_won odds = float(number_won)/number_of_games print "Estimated odds of winning : %.3f " % odds if __name__ == "__main__": from doctest import testmod testmod() main()