usr bin python Some fundamental constants 52 total cards 13 cards in c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python
# Some fundamental constants
N = 52 #total cards
C = 13 #cards in color
M = 4 #colors
K_max = 13 #desired number of cards in a hand
class Hand (list):
def __repr__(self):
res = [('%1d' % r) for r in self]
return '-'.join(res)
def __hash__ (self):
h = 0
for k in self:
h = h * C + k
return h
from copy import copy
old_hands = {Hand([1]+[0]*(M-1)):1.0} #K = 1 => (1,0,0,0) & P=1
for K in xrange(2, K_max+1): #cards in set
new_hands = {}
for h0, p0 in old_hands.iteritems():
for c in range(0,M): #adding colors
h = copy(h0); h[c] += 1;
h.sort (reverse=True)
dp = p0 * (C - h0[c])/(N - K + 1.0)
if not (h in new_hands):
new_hands[h] = 0.0
new_hands[h] += dp
old_hands = new_hands
res = [{'hand':h, 'p': p} for h,p in new_hands.iteritems ()]
def by_probability (v1,v2):
if v1['p'] > v2['p']:
return 1
if v1['p'] < v2['p']:
return -1
return 0
res.sort (cmp=by_probability, reverse=True)
for obj in res:
print 'P = %e' % obj['p'], 'H =', obj['hand']