Instantly share code, notes, and snippets.

Embed
What would you like to do?
Companion code for my Number Guessing Game article - https://aparav.github.io/2018/01/08/the-number-guessing-game/
'''
Author: Aparajithan Venkateswaran
Companion Article: https://aparav.github.io/2018/01/08/the-number-guessing-game/
'''
from scipy.special import comb
def conditional_prob(i, k, n, m):
'''
Calculates the probability of event C conditioned on Ri
'''
if m == 0:
return 0
ans = i / m
ans *= comb(m, i)
ans *= comb(n - m, k - i)
ans /= comb(n, k)
return ans
def total_prob(n, m, k):
'''
Calculates the probability of event C
'''
probability = 0.0
for i in range(0, k + 1):
probability += conditional_prob(i, k, n, m)
return probability
def checking_routine():
'''
Function to check arbitrary values of n, m, k and verify our hypothesis is true
'''
for n in range(1, 101):
for k in range(1, n + 1):
print("n = {} k = {}".format(n, k))
expected_prob = k / n
t_expected_prob = round(expected_prob, 7)
for m in range(1, n + 1):
probability = total_prob(n, m, k)
t_probability = round(probability, 7)
if t_probability != t_expected_prob:
print("Expected: {}\nGot: {}\nn = {} m = {} k = {}".format(
expected_prob, probability, n, m, k
))
return
if __name__ == "__main__":
checking_routine()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment