Return probability of k successes out of n tries, with p probability for one success The function uses the factorial function in order to calculate the binomial coefficient >>> binomial_distribution(3, 5, 0.7) 0.30870000000000003 >>> binomial_distribution (2,
(successes: int, trials: int, prob: float)
| 5 | |
| 6 | |
| 7 | def binomial_distribution(successes: int, trials: int, prob: float) -> float: |
| 8 | """ |
| 9 | Return probability of k successes out of n tries, with p probability for one |
| 10 | success |
| 11 | |
| 12 | The function uses the factorial function in order to calculate the binomial |
| 13 | coefficient |
| 14 | |
| 15 | >>> binomial_distribution(3, 5, 0.7) |
| 16 | 0.30870000000000003 |
| 17 | >>> binomial_distribution (2, 4, 0.5) |
| 18 | 0.375 |
| 19 | """ |
| 20 | if successes > trials: |
| 21 | raise ValueError("""successes must be lower or equal to trials""") |
| 22 | if trials < 0 or successes < 0: |
| 23 | raise ValueError("the function is defined for non-negative integers") |
| 24 | if not isinstance(successes, int) or not isinstance(trials, int): |
| 25 | raise ValueError("the function is defined for non-negative integers") |
| 26 | if not 0 < prob < 1: |
| 27 | raise ValueError("prob has to be in range of 1 - 0") |
| 28 | probability = (prob**successes) * ((1 - prob) ** (trials - successes)) |
| 29 | # Calculate the binomial coefficient: n! / k!(n-k)! |
| 30 | coefficient = float(factorial(trials)) |
| 31 | coefficient /= factorial(successes) * factorial(trials - successes) |
| 32 | return probability * coefficient |
| 33 | |
| 34 | |
| 35 | if __name__ == "__main__": |
no test coverage detected