import random class Card(object): def __init__(self, rank, suit): self.rank = rank self.suit = suit def getRank(self): return self.rank def getSuit(self): return self.suit def __str__(self): rank_repr = "" if self.rank == 1: rank_repr = "A" elif self.rank <= 10: rank_repr = str(self.rank) elif self.rank == 11: rank_repr = "J" elif self.rank == 12: rank_repr = "Q" elif self.rank == 13: rank_repr = "K" return rank_repr + " of " + self.suit def __repr__(self): return str(self) class Deck(object): def __init__(self): self.RANKS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] self.SUITS = ["Spades", "Diamonds", "Clubs", "Hearts"] self.full_deck = [] self.cards = [] # A full deck contains one of each rank and suit for rank in self.RANKS: for suit in self.SUITS: self.full_deck.append(Card(rank, suit)) self.shuffle() # Adds all cards to the deck and shuffles it def shuffle(self): self.cards = self.full_deck[:] random.shuffle(self.cards) # Removes the top card from the deck and returns it def draw_card(self): return self.cards.pop() # Removes the top hand_size cards from the deck and returns a list of them def draw_hand(self, hand_size): hand = [] for i in range(hand_size): hand.append(self.draw_card()) return hand # Returns whether the given hand is a flush (all cards same suit) # Assumes hand has at least one card def is_flush(hand): suit = hand[0].getSuit() for card in hand: if card.getSuit() != suit: return False return True # Returns whether the given hand is a straight (rank ordered one after the other) # Assumes hand has at least two cards def is_straight(hand): # Returns a new list sorted by rank sorted_hand = sorted(hand, key=Card.getRank) for i in range(len(sorted_hand)-1): # If it is a straight, should differ by 1 if sorted_hand[i+1].getRank() - sorted_hand[i].getRank() != 1: return False return True def flush_sim(num_trials): deck = Deck() num_flushes = 0 for trial in range(num_trials): deck.shuffle() hand = deck.draw_hand(5) if is_flush(hand): num_flushes += 1 return num_flushes/float(num_trials) def straight_sim(num_trials): deck = Deck() num_straights = 0 for trial in range(num_trials): deck.shuffle() hand = deck.draw_hand(5) if is_straight(hand): num_straights += 1 return num_straights/float(num_trials) def straight_flush_sim(num_trials): deck = Deck() num_straight_flushes = 0 for trial in range(num_trials): deck.shuffle() hand = deck.draw_hand(5) if is_flush(hand) and is_straight(hand): num_straight_flushes += 1 return num_straight_flushes/float(num_trials) ''' Inputs: num_trials - number of trials to run hand_eval - a function that takes a list of cards and returns whether that hand is a success hand_size - number of cards in each hand Returns: number of successful trials divided by num_trials ''' def card_simulator(num_trials, hand_eval, hand_size): deck = Deck() num_successes = 0 for trial in range(num_trials): deck.shuffle() hand = deck.draw_hand(hand_size) if hand_eval(hand): num_successes += 1 return num_successes/float(num_trials)