Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Card Enum and itertools solution in Clear category for Texas Referee by juestr
from enum import IntEnum
from itertools import chain, combinations, groupby
Card = IntEnum('Card', [r+s for r in '23456789TJQKA' for s in 'scdh'], start=0)
rank = lambda card: card.name[0]
suit = lambda card: card.name[1]
def texas_referee(cards_str):
def score(hand):
flush_result = hand if all(suit(c) == suit(hand[0]) for c in hand[1:]) else ()
ranks = ''.join(map(rank, hand))
straight_result = hand if ranks in 'AKQJT98765432' else hand[1:] + hand[:1] if ranks == 'A5432' else ()
groups = sorted((tuple(group) for _, group in groupby(hand, key=rank)),
key=lambda g: len(g) > 1, reverse=True)
gsig = sorted((len(groups[0]), len(groups[1])), reverse=True)
ghandif = lambda g1, g2: tuple(chain.from_iterable(groups)) if [g1, g2] == gsig else ()
return (flush_result and straight_result, ghandif(4, 1), ghandif(3, 2),
flush_result, straight_result, ghandif(3, 1), ghandif(2, 2), ghandif(2, 1), hand)
cards = sorted((Card[cs] for cs in cards_str.split(',')), reverse=True)
besthand = max(combinations(cards, 5), key=score)
return ','.join(card.name for card in besthand)
Dec. 28, 2019