10-days-of-statistics

Day 4: Binomial Distribution I

https://www.hackerrank.com/challenges/s10-binomial-distribution-1

In this challenge, we learn about binomial distributions. Check out the Tutorial tab for learning materials!

Task

The ratio of boys to girls for babies born in Russia is . If there is child born per birth, what proportion of Russian families with exactly children will have at least boys?

Write a program to compute the answer using the above parameters. Then print your result, rounded to a scale of decimal places (i.e., format).

Input Format

A single line containing the following values:

1.09 1 If you do not wish to read this information from stdin, you can hard-code it into your program.

Output Format

Print a single line denoting the answer, rounded to a scale of decimal places (i.e., format).


In [8]:
import math

In [7]:
def input():
    return "1.09 1"

ratios = [float(i) for i in input().strip().split(" ")]
probs = {"b": ratios[0] /sum(ratios), "g": ratios[1] / sum(ratios)}
probs


Out[7]:
{'b': 0.521531100478469, 'g': 0.47846889952153115}

In [96]:
def binomial_dist(x, n, p):
    q = 1.0 - p
    bernoulli = p**x * q**(n-x)
    combination = math.factorial(n) / (math.factorial(x) * math.factorial(n-x))
    return combination * bernoulli

In [100]:
[(i, binomial_dist(4, 10, 0.5)) for i in range(3, 15)]


Out[100]:
[(3, 0.14185279138557705),
 (4, 0.27148922037702816),
 (5, 0.32474861818449163),
 (6, 0.3107649426854674),
 (7, 0.2602104787217523),
 (8, 0.19920465240639484),
 (9, 0.1429701750553316),
 (10, 0.09772419951246358),
 (11, 0.06429238439350161),
 (12, 0.04101596954767829),
 (13, 0.025512384234320916),
 (14, 0.015536067889485214)]

In [109]:
print("{0:.3f}".format(sum([binomial_dist(i, 6, probs["b"]) for i in range(3, 7)])))


0.696

In [ ]: