In [1]:
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 [10]:
def hand_percentages(n=700*1000):
    "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(hand_names[i], 100.*counts[i]/n)

hand_percentages(1000*1000)


5 of a Kind 0.0
Straight Flush 0.0012
 0.0
4 of a Kind 0.0251
Full House 0.1464
Flush 0.2029
Straight 0.3919
3 of a Kind 2.1117
2 Pair 4.754
Pair 42.311
High Card 50.0558

In [35]:
# 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))


['JS', '5D'] [['6H', 'KH', '3D', '4D', '5H'], ['3H', '4H', '7C', '4S', '9D'], ['5C', 'JC', '3S', '6S', '5S'], ['QC', 'AD', 'QH', 'QS', 'KS']]
((1, (5, 13, 11, 6)), ('6H', 'KH', '5H', 'JS', '5D'))
((1, (4, 11, 9, 7)), ('4H', '7C', '4S', '9D', 'JS'))
((6, (5, 11)), ('5C', 'JC', '5S', 'JS', '5D'))
((3, (12, 14, 13)), ('QC', 'AD', 'QH', 'QS', 'KS'))
winner:  ((6, (5, 11)), ('5C', 'JC', '5S', 'JS', '5D'))

In [21]:


In [ ]: