Skip to content

Instantly share code, notes, and snippets.

@marethyu
Created February 4, 2023 10:20
Show Gist options
  • Save marethyu/777e372c69cb356c5fc8c93f59cf62e6 to your computer and use it in GitHub Desktop.
Save marethyu/777e372c69cb356c5fc8c93f59cf62e6 to your computer and use it in GitHub Desktop.
# Draw 5 cards from the standard deck of 52 cards. Denote random variables X to be the number of black cards in the hand and Y to be the number of spades in the hand.
from math import comb
from pandas import DataFrame
nways = comb(52, 5)
joint_pmf = [[0.0 for x in range(7)] for y in range(7)]
total = 0.0
# populate the joint_pmf
for y in range(6):
for x in range(y + 1):
joint_pmf[y][x] = comb(13, x) * comb(13, y - x) * comb(26, 5 - y) / nways
total += joint_pmf[y][x]
print(f'total probability for p_XY is {total}')
EX = 0
total = 0.0
# calculate marginal pmf for X
for x in range(6):
px = 0.0
for y in range(6):
px += joint_pmf[y][x]
joint_pmf[6][x] = px
EX += x * px
total += px
print(f'total probability for p_X is {total} and expectation is {EX}')
EY = 0
total = 0.0
# calculate marginal pmf for Y
for y in range(6):
py = 0.0
for x in range(6):
py += joint_pmf[y][x]
joint_pmf[y][6] = py
EY += y * py
total += py
print(f'total probability for p_Y is {total} and expectation is {EY}')
print(DataFrame(joint_pmf))
covXY = 0
for y in range(6):
for x in range(y + 1):
covXY += (x - EX) * (y - EY) * joint_pmf[y][x]
print(f'Cov(X,Y)={covXY}')
EXY = 0
for y in range(6):
for x in range(y + 1):
EXY += x * y * joint_pmf[y][x]
print(f'Cov(X,Y)={EXY - EX * EY}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment