~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

OA: Three-card game

easy 2 levels ~30 min OpenAI

Level 1 Rank and compare three-card hands

A two-player card game uses three-card hands. A card is a string: its rank followed by one suit letter.

  • Ranks, weakest to strongest: 2 3 4 5 6 7 8 9 10 J Q K A.
  • Suits: S, H, D, C. Suits never affect strength.

Examples: "10H", "QS", "2C", "AD".

A hand is exactly three cards and falls into one category, strongest first:

  1. "three of a kind": all three ranks equal.
  2. "pair": exactly two ranks equal.
  3. "high card": three different ranks.

Implement two functions:

  • category(hand: list[str]) -> str: the hand's category name as written above.
  • compare_hands(hand1: list[str], hand2: list[str]) -> int: 1 if hand1 is stronger, 2 if hand2 is stronger, 0 if they are equally strong.

Strength: a better category always wins. Within the same category:

  • three of a kind: the higher rank wins;
  • pair: compare the paired rank, then the odd card;
  • high card: compare the highest ranks, then the middle ones, then the lowest.

Both functions raise ValueError if a hand doesn't have exactly three cards or contains a malformed card (unknown rank or suit, such as "1H", "11S", "QX", "Q"). Card strings are case-sensitive: "qs" is malformed.

category(["7H", "7S", "7D"])                          # "three of a kind"
category(["KH", "2S", "KD"])                          # "pair"
compare_hands(["2H", "2S", "3D"], ["AH", "KS", "QD"]) # 1   (any pair beats high card)
compare_hands(["9H", "9S", "4D"], ["9D", "9C", "3S"]) # 1   (same pair, kicker 4 > 3)
compare_hands(["AH", "7S", "2D"], ["AS", "7D", "3C"]) # 2   (A = A, 7 = 7, 2 < 3)
compare_hands(["10H", "JS", "QD"], ["QC", "JH", "10S"]) # 0 (order and suits don't matter)
compare_hands(["10H", "JS"], ["QC", "JH", "10S"])     # ValueError
Show hint

Map each rank to a number (2..14). A hand's strength can be one tuple: (category_number, ranks...) where the ranks are ordered by (how often they appear, value), descending. Then comparing hands is comparing tuples.

Level 2 unlocks when level 1 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc