In [3]:
import random
import itertools
def deal(numhands, n=5, whole_cards=0, deck = [r+s for r in '23456789TJQKA' for s in 'SHDC']):
random.shuffle(deck)
return [deck[n*i:n*(i+1)] for i in range(numhands)], deck[-1-whole_cards:-1]
def hand_rank(hand):
"Return a value indicating how high the hand ranks."
# counts is the count of each rank; ranks lists corresponding ranks
# e.g. '7 T 7 9 7' => counts = (3, 1, 1); ranks = (7, 10, 9)
groups = group(['--23456789TJQKA'.index(r) for r,s in hand])
counts, ranks = unzip(groups)
if ranks == (14, 5, 4, 3, 2):
ranks = (5, 4, 3, 2, 1)
straight = len(ranks) == 5 and max(ranks)-min(ranks) == 4
flush = len(set([s for r,s in hand])) == 1
return max(count_rankings[counts], 4*straight + 5*flush), ranks
count_rankings = {(5,):10, (4, 1):7, (3, 2):6, (3, 1, 1):3, (2, 2, 1):2, (2, 1, 1, 1):1, (1, 1, 1, 1, 1):0}
def group(items):
"Return a list of [(count, x)...], highest count first, then highest x first."
groups = [(items.count(x), x) for x in set(items)]
return sorted(groups, reverse=True)
def unzip(pairs): return zip(*pairs)
hand_names = ['High Card', 'Pair', '2 Pair', '3 of a Kind', 'Straight', 'Flush', 'Full House', '4 of a Kind', '***', 'Straight Flush', '5 of a Kind']
In [5]:
def hand_percentages(n=700):
"Sample n random hands and print a table of percentages for each type of hand."
counts = [0] * 11
for i in range(n):
cards_dealt, whole_cards = deal(1)
for hand in cards_dealt:
ranking = hand_rank(hand)[0]
counts[ranking] += 1
for i in reversed(range(11)):
print('{}: {:.3%}'.format(hand_names[i], counts[i]/n))
hand_percentages(700)
In [7]:
# 7-card Stud using a deal(players, cards, whole cards)
cards_dealt, whole_cards = deal(4, 5, 2)
print (whole_cards, cards_dealt)
winner = []
for player in cards_dealt:
player_hand_ranks = []
for hand in itertools.combinations(player + whole_cards, 5):
player_hand_ranks.append((hand_rank(hand), hand))
best_hand = max(player_hand_ranks)
print(best_hand)
winner.append(best_hand)
print( 'winner: ', max(winner))
In [4]:
In [ ]: