Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Group by hands, then find maximum value. solution in Clear category for Texas Referee by han97
RANKS_REVERSED = 'AKQJT98765432'
RANKS = '23456789TJQKA'
SUITS_REVERSED = "hdcs"
SUITS = 'scdh'
def texas_referee(cards_str):
def is_straight_flush(hand):
return is_straight(hand) and is_flush(hand)
def is_straight(hand):
return "".join(c[0] for c in hand) in RANKS_REVERSED
def is_flush(hand):
return len(set(c[1] for c in hand)) == 1
def is_number_of_a_kind(hand, num): # is four/three of a kind
ranks = [c[0] for c in hand]
for rank, suit in hand:
if ranks.count(rank) == num:
return True
return False
def is_full_house(hand):
ranks = [c[0] for c in hand]
s = set(ranks)
if len(s) == 2:
return ranks.count(s.pop()) == 3 or ranks.count(s.pop()) == 3
def is_two_pair(hand):
ranks = [c[0] for c in hand]
s = set(ranks)
if len(s) == 3:
return sum(ranks.count(x) for x in s) == 5
def is_one_pair(hand):
return len(set(c[0] for c in hand)) == 4
def compare(x, y):
diff = RANKS_REVERSED.index(x[0]) - RANKS_REVERSED.index(y[0])
if diff:
return diff
return SUITS_REVERSED.index(x[1]) - SUITS_REVERSED.index(y[1])
from itertools import combinations
cards_str = sorted(cards_str.split(','), cmp=compare)
hands_by_rank = [[] for _ in range(10)]
for hand in combinations(cards_str, 5):
if is_straight_flush(hand):
hands_by_rank[0].append(hand)
elif is_number_of_a_kind(hand, 4):
hands_by_rank[1].append(hand)
elif is_full_house(hand):
hands_by_rank[2].append(hand)
elif is_flush(hand):
hands_by_rank[3].append(hand)
elif is_straight(hand):
hands_by_rank[4].append(hand)
elif is_number_of_a_kind(hand, 3):
hands_by_rank[5].append(hand)
elif is_two_pair(hand):
hands_by_rank[6].append(hand)
elif is_one_pair(hand):
hands_by_rank[7].append(hand)
else:
hands_by_rank[8].append(hand)
for hands in hands_by_rank:
if hands:
return ",".join(max(hands, key=lambda h: sum(RANKS.index(r) * 2 + SUITS.index(s) for r, s in h)))
Aug. 15, 2016
Comments: