https://www.hackerrank.com/challenges/s10-binomial-distribution-2
In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.
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?
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.
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]:
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]:
In [47]:
[(i, round(binomial_dist(i, 100, .12), 6)) for i in range(1, 20)]
Out[47]:
In [ ]: