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)


5 of a Kind:        0.000%
Straight Flush:        0.000%
***:        0.000%
4 of a Kind:        0.000%
Full House:        0.000%
Flush:        0.143%
Straight:        0.429%
3 of a Kind:        1.429%
2 Pair:        4.857%
Pair:        40.429%
High Card:        52.714%

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))


['AD', 'KD'] [['KH', '9D', '7H', 'TH', '5D'], ['JD', 'QD', '4C', '4D', '3C'], ['TD', '8H', 'KS', 'QS', '8C'], ['TS', 'QH', 'JS', 'AS', '2D']]
((1, (13, 14, 10, 9)), ('KH', '9D', 'TH', 'AD', 'KD'))
((5, (14, 13, 12, 11, 4)), ('JD', 'QD', '4D', 'AD', 'KD'))
((2, (13, 8, 14)), ('8H', 'KS', '8C', 'AD', 'KD'))
((4, (14, 13, 12, 11, 10)), ('TS', 'QH', 'JS', 'AS', 'KD'))
winner:  ((5, (14, 13, 12, 11, 4)), ('JD', 'QD', '4D', 'AD', 'KD'))

In [4]:


In [ ]: