# EulerProblem054

# Problem Name (Euler Problem 54)¶

Back to overview.

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:

- High Card: Highest value card.
- One Pair: Two cards of the same value.
- Two Pairs: Two different pairs.
- Three of a Kind: Three cards of the same value.
- Straight: All cards are consecutive values.
- Flush: All cards of the same suit.
- Full House: Three of a kind and a pair.
- Four of a Kind: Four cards of the same value.
- Straight Flush: All cards are consecutive values of same suit.
- Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
- The cards are valued in the order:
- 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.

Consider the following five hands dealt to two players:

Hand | Player 1 | Player 2 | Winner
--- | --- | --- | ---
1 | 5H 5C 6S 7S KD Pair of Fives | 2C 3S 8S 8D TD Pair of Eights | Player 2
2 | 5D 8C 9S JS AC Highest card Ace | 2C 5C 7D 8S QH Highest card Queen | Player 1
3 | 2D 9C AS AH AC Three Aces | 3D 6D 7D TD QD Flush with Diamonds | Player 2
4 | 4D 6S 9H QH QC Pair of Queens Highest card Nine | 3D 6D 7H QD QS Pair of Queens Highest card Seven | Player 1
5 | 2H 2D 4C 4D 4S Full House With Three Fours | 3C 3D 3S 9S 9D Full House with Three Threes | Player 1

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.

How many hands does Player 1 win?

Let's start with some helper functions.

In [21]:

    def suit_to_value(suit):
        return {
            "2": 2,
            "3": 3,
            "4": 4,
            "5": 5,
            "6": 6,
            "7": 7,
            "8": 8,
            "9": 9,
            "T": 10,
            "J": 11,
            "Q": 12,
            "K": 13,
            "A": 14,
        }[suit]

    assert(suit_to_value('K') == 13)

    def is_flush(colors):
        first_color = colors[0]
        for color in colors:
            if color != first_color:
                return False
        return True

    assert(is_flush(["H", "H", "H", "H", "H"]))
    assert(is_flush(["H", "H", "D", "H", "H"]) == False)

    def is_straight(suits):
        suits = sorted(suits)
        first_suit = suits[0]
        for suit in suits[1:]:
            if first_suit + 1 != suit:
                return False
            first_suit = suit
        return True

    assert(is_straight([6,3,4,5,7]))
    assert(is_straight([6,3,4,5,8]) == False)

In [37]:

    def get_numbered_groups(ns):
        """ Takes [0, 3, 0, 3, 1] and returns
            [(2, 3), (2, 0), (1, 1)]
        """
        rs = []
        current_group = []
        for n in sorted(ns, reverse=True):
            if not current_group or n in current_group:
                current_group.append(n)
            else:
                rs.append(current_group)
                current_group = [n]
        rs.append(current_group)
        rs = sorted([(len(r), r[0]) for r in rs], reverse=True)
        return rs

    assert(get_numbered_groups([0, 3, 0, 3, 1]) == [(2, 3), (2, 0), (1, 1)])

Let's put that stuff together.

In [45]:

    def rank(hand):
        """ A hand must be provided as a list of two letter strings.
            The first letter is the suit and the second the suit of a card.

            The function returns a tuple. The first value represents the hand as an integer
            where 0 means high card and 9 means Straight Flush.  The second value is a list of integers
            ranking the value of the respective rank. For example, a Royal Flush would be (9, [14, 13, 12, 11, 10]),
            while 22aqj would be (1, [2, 2, 14, 12, 11]). By doing this we can simply compare to hands
            by first comparing the rank itself and then the list of integers.

            We get something like ["5H", "6S", "7S", "5C", "KD"].
        """

        suits, colors = zip(*(map(lambda s: (s[0], s[1]), hand)))
        suits = sorted(map(suit_to_value, suits))

        flush = is_flush(colors)
        straight = is_straight(suits)
        numbered_suits = get_numbered_groups(suits)
        if flush and straight:
            return [8, numbered_suits]
        if flush:
            return [5, numbered_suits]
        if straight:
            return [4, numbered_suits]
        if numbered_suits[0][0] == 4:
            return [7, numbered_suits]
        if numbered_suits[0][0] == 3 and numbered_suits[1][0] == 2:
            return [6, numbered_suits]
        if numbered_suits[0][0] == 3:
            return [3, numbered_suits]
        if numbered_suits[0][0] == 2 and numbered_suits[1][0] == 2:
            return [2, numbered_suits]
        if numbered_suits[0][0] == 2:
            return [1, numbered_suits]
        return [0, numbered_suits]

In [55]:

    assert(rank(["5H", "5C", "6S", "7S", "KD"]) == [1, [(2, 5), (1, 13), (1, 7), (1, 6)]])          # Pair of Fives
    assert(rank(["5D", "8C", "9S", "JS", "AC"]) == [0, [(1, 14), (1, 11), (1, 9), (1, 8), (1, 5)]]) # Highest card Ace
    assert(rank(["2D", "9C", "AS", "AH", "AC"]) == [3, [(3, 14), (1, 9), (1, 2)]])                  # Three Aces
    assert(rank(["4D", "6S", "9H", "QH", "QC"]) == [1, [(2, 12), (1, 9), (1, 6), (1, 4)]])          # Pair of Queens Highest card Nine
    assert(rank(["2H", "2D", "4C", "4D", "4S"]) == [6, [(3, 4), (2, 2)]])                           # Full House With Three Fours
    assert(rank(["2C", "3S", "8S", "8D", "TD"]) == [1, [(2, 8), (1, 10), (1, 3), (1, 2)]])          # Pair of Eights
    assert(rank(["2C", "5C", "7D", "8S", "QH"]) == [0, [(1, 12), (1, 8), (1, 7), (1, 5), (1, 2)]])  # Highest card Queen
    assert(rank(["3D", "6D", "7D", "TD", "QD"]) == [5, [(1, 12), (1, 10), (1, 7), (1, 6), (1, 3)]]) # Flush with Diamonds
    assert(rank(["3D", "6D", "7H", "QD", "QS"]) == [1, [(2, 12), (1, 7), (1, 6), (1, 3)]])          # Pair of Queens Highest card Seven
    assert(rank(["3C", "3D", "3S", "9S", "9D"]) == [6, [(3, 3), (2, 9)]])                           # Full House with Three Threes

In [67]:

    def read_hands():
        """ Reads a list of tuples where each field
            in the tuple represents a hand.
        """
        hands = []
        with open("EulerProblem054.txt", "r") as f:
            for line in f.readlines():
                cards = line.strip().split(" ")
                hands.append((cards[:5], cards[5:]))
        return hands

    p1_wins = 0

    for p1_hand, p2_hand in read_hands():
        if rank(p1_hand) > rank(p2_hand):
            p1_wins += 1
            msg = "P1 hand {} wins over P2 hand {}."
            #print(msg.format(p1_hand, p2_hand))
        else:
            msg = "P1 hand {} loses versus P2 hand {}."
            #print(msg.format(p1_hand, p2_hand))

    s = p1_wins

In [70]:

    print(s)
    assert(s == 376)

    376

In [ ]: