""" craps - work in class 2012 """ from random import randint debug = False def print_debug(message): if debug: print " debug: ", message def d6(): """ Return number from a 6-sided die >>> x = d6() >>> x <= 6 and x >= 1 True """ return randint(1,6) def two_dice(): """ Return sum from two 6-sided dice """ # Note: this is *not* the same as randint(2,12) return d6() + d6() def play_game(): """ Play a game of craps. Return True if you win. """ first_roll = two_dice() print_debug(" first roll = " + str(first_roll)) if first_roll in [2, 3, 12]: print_debug(" loses on first roll") return False elif first_roll in [7, 11]: print_debug(" wins on first roll") return True else: point = first_roll print_debug(" point is " + str(point)) while True: next_roll = two_dice() print_debug(" next roll is " + str(next_roll)) if next_roll == point: print_debug(" won with that point") return True elif next_roll == 7: print_debug(" lost") return False def play_n_games(n): """ Return number of games won out of n """ n_wins = 0 for i in range(n): if play_game(): n_wins = n_wins + 1 return n_wins def odds(m_sets, n_games): """ Return list of m odds, each set is n games""" result = [] for i in range(m_sets): n_wins = play_n_games(n_games) result = result + [float(n_wins) / n_games] # result.append(float(n_wins) / n_games) # same return result # Python already has this as min() # #def minimum(numbers): # """ Return smallest of a list of numbers """ # smallest = numbers[0] # for n in numbers: # if n < smallest: # smallest = n # return smallest def main(): print "--- Estimated odds of winning at craps ---" n_games = input("How many games would you like to simulate? ") print "Simulating", n_games, "games ..." n_won = play_n_games(n_games) print "done." print "Number of simulated wins:", n_won print "Estimated odds of winning:", float(n_won)/n_games print "--- Estimated error ---" m_sets = input("How many times would you like to repeat " + "that series of " + str(n_games) + " games? ") print "Simulating", m_sets, " sets of", n_games, "games ..." list_of_odds = odds(m_sets, n_games) lowest = min(list_of_odds) # aboe started to write minimum() highest = max(list_of_odds) print "Lowest estimated odds:", lowest print "Highest estimated odds:", highest print "Error range = (high - low)", (highest - lowest) if __name__ == "__main__": import doctest doctest.testmod() main()