OpenAI questions

Poker Simulation

OpenAIPhone screenMedium

You run a game of three-card poker for several players and return a log of what happened, in order.

A card is a string made of a rank and a suit: "12H" is rank 12, suit H. Ranks are 2 to 13 (11, 12 and 13 stand for J, Q and K; there are no aces) and suits are H, D, C, S. The deck lists cards in the order they are dealt, and no card appears twice.

Cards are dealt one at a time, taking the next card from the deck each time and going round the table in the order of players: every player gets a first card, then every player a second, then every player a third. Cards left in the deck after that are not used.

The log is a list of strings, in this order:

  1. One line per card dealt: <player> is dealt <card>.
  2. One line per player, in player order: <player> has <card> <card> <card>: <category>, with the cards in the order they were dealt.
  3. The result line.

Part 1: Compare hands

The suit is part of the card text. Suits never affect the ranking. Hands rank, from best to worst: three of a kind (category three of a kind), a pair (pair), then a high card (high card).

Within a category the better hand is the one with the higher rank. For three of a kind that is the rank of the three cards. For a pair it is the rank of the pair, then the rank of the remaining card. For a high card it is the highest rank, then the middle one, then the lowest. Hands that are equal under these rules tie, and suits never break a tie.

The result line is Winner: <player>, or Tie: <player>, <player> listing every tied player in the order of players.

Implement play(players, deck).

  1. Example 1
    players
    ["Alice","Bob","Cara"]
    deck
    ["12H","11H","9H","12D","11D","9D","5S","11S","9S"]
    Output
    ["Alice is dealt 12H","Bob is dealt 11H","Cara is dealt 9H","Alice is dealt 12D","Bob is dealt 11D","Cara is dealt 9D","Alice is dealt 5S","Bob is dealt 11S","Cara is dealt 9S","Alice has 12H 12D 5S: pair","Bob has 11H 11D 11S: three of a kind","Cara has 9H 9D 9S: three of a kind","Winner: Bob"]

    Why: Alice holds a pair of queens, Bob three jacks and Cara three nines. Three of a kind beats a pair whatever the ranks are, and jacks beat nines, so the log ends with Winner: Bob.

Constraints

  • 2 <= len(players) <= 6, and player names are unique
  • len(deck) >= 3 * len(players)
  • No card appears twice in deck
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Poker Simulation: OpenAI interview question | LoopCoach