Poker hand checker with jokers
Write is_valid_hand(hand: list[str]) -> bool for a five-card poker game.
Each card is a string "<rank> of <suit>". The rank is 2 to 10, J, Q, K or A. The suit is hearts, diamonds, clubs or spades. A hand has exactly 5 cards from one standard 52-card deck.
A hand is valid if it forms at least one of these patterns:
-
Straight: five consecutive ranks, any suits. The ace can be high (
10 J Q K A) or low (A 2 3 4 5), but ranks do not wrap (Q K A 2 3is not a straight). - Flush: all five cards share a suit.
- Straight flush: both of the above.
- Four of a kind: four cards of the same rank.
- Full house: three cards of one rank and two of another.
Any other hand (a pair, two pair, three of a kind, high card) is not valid. Raise an error for malformed input: the wrong number of cards, an unknown rank or suit, or the same card twice.
Example 1
["9 of clubs", "7 of hearts", "8 of clubs", "J of spades", "10 of diamonds"] -> True (straight 7-J)
Example 2
["Q of hearts", "Q of spades", "5 of clubs", "5 of hearts", "Q of diamonds"] -> True (full house)
["Q of hearts", "Q of spades", "5 of clubs", "5 of hearts", "2 of diamonds"] -> False (two pair)
Part 2. The game adds jokers, written "Joker". A joker stands for any card you choose. With jokers a hand can also be five of a kind (counts as valid). For example, ["Joker", "4 of clubs", "5 of spades", "7 of hearts", "8 of hearts"] is a straight with the joker as a 6. Avoid trying every possible replacement.
Part 3. Return the name of the strongest pattern the hand makes (or none), not just a bool.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
