Day 4: Binomial Distribution II

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

Objective

In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.

Task

A manufacturer of metal pistons finds that, on average, %12 of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of 10 pistons will contain:

No more than 2 rejects? At least 2 rejects?

Input Format

A single line containing the following values (denoting the respective percentage of defective pistons and the size of the current batch of pistons):

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

Output Format

Print the answer to each question on its own line:

The first line should contain the probability that a batch of pistons will contain no more than rejects. The second line should contain the probability that a batch of pistons will contain at least rejects. Round both of your answers to a scale of decimal places (i.e., format).


In [7]:
import math

In [12]:
def input():
    return "12 10"

inputs = [float(i) for i in input().strip().split(" ")]
rejects_prob = inputs[0] / 100
trial = inputs[1]
rejects, trial


Out[12]:
(0.12, 10.0)

In [43]:
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 [18]:
at_least_2 = sum(binomial_dist(i, trial, rejects_prob) for i in range(2, 11))

In [21]:
at_most_2 = sum(binomial_dist(i, trial, rejects_prob) for i in range(1, 3))

In [22]:
at_least_2, at_most_2


Out[22]:
(0.3417249657959586, 0.6128172302686224)

In [47]:
[(i, round(binomial_dist(i, 100, .12), 6)) for i in range(1, 20)]


Out[47]:
[(1, 3.8e-05),
 (2, 0.000258),
 (3, 0.001151),
 (4, 0.003806),
 (5, 0.009965),
 (6, 0.021516),
 (7, 0.039399),
 (8, 0.062456),
 (9, 0.08706),
 (10, 0.108033),
 (11, 0.120533),
 (12, 0.121903),
 (13, 0.112526),
 (14, 0.095355),
 (15, 0.07455),
 (16, 0.054006),
 (17, 0.036389),
 (18, 0.022881),
 (19, 0.013466)]

In [ ]: