Solution to: [Day 4: Geometric Distribution II](https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem)

<h1 id="tocheading">Table of Contents</h1>
<div id="toc"></div>

- Table of Contents
- Math Solution
- Solution
    - Imports
    - Input
    - Geometric Distribution
    - Format
    - Main


```javascript
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
```


    <IPython.core.display.Javascript object>


# Math Solution

The probability that a machine produces a defective product is 1/3. What is the probability that the 1st defect is found during the first 5 inspections?

There are two methods to solve this:
- use a summation of the geom_prob() function
- or, because the trials are independent, we can instead calculate the complement of the success rate to the power of n

\begin{equation}
= 1 - (1 - \frac{1}{3}) ^ {5}
\end{equation}

# Solution

## Imports


```python
from typing import Tuple
```

## Input


```python
def get_input() -> Tuple[float, int]:
	"""Return input for Day 4: Geom Dist II.

	Returns:
		Tuple[float, int]: p and n, respectively
	"""
	num, denom = [int(x) for x in input().split()]
	p = num/denom
	n = int(input())
	return (p, n)
```

## Geometric Distribution


```python
def calc_geom_dist(n: int, p: float) -> float:
	"""Returns probability mass of geom distribution for n, p

	Args:
		n (int): number of trials
		p (float): p(x)

	Returns:
		float: Probability of geom dist given n, p
	"""
	q = 1 - p
	return q ** (n-1) * p
```


```python
def get_cum_geom_prob(n: int, p: float) -> float:
	"""Returns cumulative probability of geometric distribution in n trials

	Args:
		n (int): total number of trials
		p (float): P(x)

	Returns:
		float: Cumulative probability of x in n trials
	"""
	cum_prob = 0

	for i in range(1, n + 1):
		geom_prob = calc_geom_dist(i, p)
		cum_prob += geom_prob
	return cum_prob
```

## Format


```python
def format_scale(num: float) -> float:
	"""Returns number with decimals formatted to scale

	Args:
		num (float): Number to format

	Returns:
		float: Number formatted to scale
	"""
	return f'{num:.3f}'
```

## Main


```python
def main():
	p, n = get_input()

	cum_prob = get_cum_geom_prob(n, p)
	print(format_scale(cum_prob))
```


```python
if __name__ == "__main__":
	main()
```

    1 3
    5
    0.868


5699a8326490e9a41a40d3ff00eb8129002f0082
ipynb
Jupyter Notebook
statistics/10_days/15_day4geometricdistributionii.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
statistics/10_days/15_day4geometricdistributionii.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
statistics/10_days/15_day4geometricdistributionii.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
2021-09-22T11:06:58.000Z
2022-01-25T09:29:24.000Z
Qwen/Qwen-72B
1. YES
2. YES