# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] id="XeV1U7GkVNZY"
# ## **Importing necessary libraries**

# + id="219CEYUFVNZn"
#import the important packages
import pandas as pd #library used for data manipulation and analysis
import numpy as np # library used for working with arrays.
import matplotlib.pyplot as plt # library for plots and visualisations
import seaborn as sns # library for visualisations
# %matplotlib inline 

import scipy.stats as stats # this library contains a large number of probability distributions as well as a growing library of statistical functions.

# + [markdown] id="zwbR4fdpVNZp"
# # **Binomial Distribution**

# + [markdown] id="iLvUFh_6VNZp"
# ### **1) A LED bulb manufacturing company regularly conducts quality checks at specified periods on the products it manufactures.  Historically, the failure rate for LED light bulbs that the company manufactures is 5%. Suppose a random sample of 10 LED light  bulbs is selected. Find the probability distribution for the defective bulbs and answer the below asked questions.** 

# + id="Pnp7Np_VVNZp"
p   =  0.05 # failure rate for LED light bulbs that the company manufactures is 5%
n   =  10 # sample size
k   =  np.arange(0,11) # an array of different possible number of defective bulbs

# + id="7tAFDju8VNZq"
binomial = stats.binom.pmf(k,n,p)

# + colab={"base_uri": "https://localhost:8080/"} id="D3FonjHuVNZq" outputId="f21b8862-d653-4d28-b37c-20e9de4f5e83"
print(binomial)

# + [markdown] id="So2fXK6AZ-Xs"
# **Plot the binomial distribution**

# + colab={"base_uri": "https://localhost:8080/", "height": 297} id="EucEco3yZx0y" outputId="b00545a9-433f-41a5-cf75-107887eff0e8"
# plot the distribution
plt.bar(k,binomial)
plt.title('Binomial: n=%i , p=%.2f' % (n,p), fontsize=15)
plt.xlabel('Number of Successes')
plt.ylabel('Probability of Successes')
plt.show()

# + [markdown] id="U8C34C7HVNZr"
# **a) What is the probability that none of the LED bulbs are defective?**

# + colab={"base_uri": "https://localhost:8080/"} id="DYBa2d2kVNZs" outputId="d96b3b97-cf0c-413f-d99b-f169f4992202"
print('The probability that none of the LED bulbs are defective is %1.4f' %binomial[0])

# + [markdown] id="siKk2kFfVNZs"
# **b) What is the probability that exactly one of the LED bulbs is defective?**

# + colab={"base_uri": "https://localhost:8080/"} id="JvlpPRafVNZt" outputId="82865149-c0c5-4ad7-bf33-243dc8b09041"
print('The probability that exactly one of the LED bulbs is defective is %1.4f' %binomial[1])

# + [markdown] id="sTKTp_VbVNZt"
# **c) What is the probability that two or fewer of the LED bulbs are defective?**

# + [markdown] id="_ETr7cSsVNZu"
# Hint: 
# We need to calculate cumulative probability of two or fewer LED bulbs being defective

# + id="4j7cFmgqVNZu"
cumulative_binomial = stats.binom.cdf(k,n,p)

# + colab={"base_uri": "https://localhost:8080/"} id="ohej5x5tVNZv" outputId="25510879-1185-48f6-d11d-4f90d7d39b32"
print('The probability that two or fewer of the LED bulbs are defective is %1.4f' %cumulative_binomial[2])

# + [markdown] id="6D3d7vgNVNZv"
# **d) What is the probability that three or more of the LED bulbs are defective**

# + [markdown] id="-EnDIeiTVNZv"
# Hint: We need to subtract the cumulative probability up to 2 defective LED bulbs from 1.

# + colab={"base_uri": "https://localhost:8080/"} id="mvuUJchzVNZw" outputId="6eb39eb3-0aa2-4af7-a8ad-ab4719f925d9"
P = 1- cumulative_binomial[2]
print('The probability that three or more of the LED bulbs are defective is %1.4f' % P)

# + [markdown] id="g7pg-lWiVNZx"
# ### **2) During an NBA game a basketball player has two foul shots (free throw), if he converts 93% of his free throw shots.**

# + id="lxT7-cFZVNZx"
success=0.93

# + [markdown] id="I1yejxesVNZx"
# **a) What is the probability that he will convert both the shots?**

# + colab={"base_uri": "https://localhost:8080/"} id="SmwMFMOwVNZx" outputId="3ef552e8-2b2a-4bb7-da18-e9c00bbcbfc5"
print('The probability that he will convert both the shots is',round(stats.binom.pmf(2,2,0.93),4))

# + [markdown] id="0R1FriOVVNZy"
# **b) What is the probability that he will convert at least one shot?**

# + colab={"base_uri": "https://localhost:8080/"} id="LHvHcZIZVNZy" outputId="a07246a6-7cfa-4192-9814-2cf9f5793de3"
print('The probability that he will convert at least one shot is',round((1 - stats.binom.cdf(0,2,0.93)),4))

# + [markdown] id="jeGWrHJhabri"
# ### **3)	Over a long period  in a large multinomial corporation, 10% of all sales trainees are rated as outstanding, 75% are rated as excellent, 10% are rated as satisfactory and 5% are considered unsatisfactory. Find the following probabilities for a sample of 10 trainees selected at random:**

# + [markdown] id="f0-NPUBiVNaG"
# **a) Two are rated as outstanding**

# + id="nJhIbOHmabrl" outputId="32c1e229-fe87-4702-f764-d2133622b0a1"
p=0.1
n=10
k=2
binomial = stats.binom.pmf(k,n,p)
print('Probability of two are rated as outstanding is %1.5f' % binomial )

# + [markdown] id="RZCEMFSrVNaG"
# **b) Two or more are rated as outstanding**

# + id="KxHPMtooabrw" outputId="d1905403-3b31-4912-d72f-2b45519ba155"
#For this we will use cumulative probability
p=0.1
n=10
k=1
##To  answer this we need to calculate cumulative probability 
binomial = stats.binom.cdf(k,n,p)
#since we have calculated for 1 or less, for two or more we will subtract this prob from 1
print('Probability of two or more are rated as outstanding is %1.5f' % (1-binomial))


# + [markdown] id="u5_21Ab8VNaH"
# **c) Eight of the ten are rated either outstanding or excellent**

# + id="hUf08sVQabr3" outputId="04cac182-33f8-42b0-f9c4-eb5bc342cff5"
#prob of excellent & outstanding is 75+10
p=0.85
n=10
k=8
binomial = stats.binom.pmf(k,n,p)
print('Probability of eight out of ten are rated excellent & outstanding is %1.5f' % binomial )

# + [markdown] id="by_BuepFVNaH"
# **d) None of the trainees are rated as unsatisfactory**

# + id="RHtn4WYzabsA" outputId="e9aa51f1-1a69-44a0-8895-b05c12f4b2b7"
p=0.05
n=10
k=0
binomial = stats.binom.pmf(k,n,p)
print('Probability of no trainees are unsatisfactory is %1.5f' % binomial )

# + [markdown] id="1-lP_U28aUuP"
# # **Uniform Distribution**
#
# ### **1) A University records the amount of time  students take  to solve the statistics assignment in 'assignment.csv’. Plot the probability distribution this data follows and answer the following questions.**
#
#
#
#
#

# + [markdown] id="l46Ul-hMd7DD"
# #### **Reading the Data into the Dataframe**

# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="C1zqTRCLd6BQ" outputId="266bf3e5-3adf-4b1c-a5e4-3d1311bc6750"
assignment = pd.read_csv('assignment.csv')
assignment.head()

# + [markdown] id="UOGOuJgoeZ7X"
# Let's plot the histogram of data along with the PDF of uniform distribution using the parameters minimum time required and maximum time required for completing the assignment.

# + colab={"base_uri": "https://localhost:8080/", "height": 295} id="vtJZKDfReeL_" outputId="ad59930a-527f-48b2-9080-19c6c792f581"
# visualize the distribution of the time needed for completing the assignment
plt.hist(assignment['Time_taken'],  density=True)
plt.axhline(1/3, color = 'red')
plt.xlabel('Time required for completing the assignment')
plt.ylabel('Probability')
plt.title('Data Distribution')
plt.show()

# + [markdown] id="NYP6WplCju7J"
# **Insight**: As you can see from the above plot that all the values between 1 and 4 are having almost equal probability, we are going to use continuous uniform distribution. We need to decide the endpoints. Here, endpoints are 1 and 4.
#
# X ~ U(1, 4)

# + id="08xUp223kAeo"
# import the required function
from scipy.stats import uniform
# use the uniform.pmf() function to generate the probability distribution
x = np.linspace(1, 4, 50)
probs = uniform.pdf(x, loc = 1, scale = 3)

# + [markdown] id="riMH9942kyzJ"
# **a) Find the probability that a randomly selected Student  requires atmost 2.5 hours to complete the assignment.**
#
#
#
# **CDF:** of a random variable(X) is the probability that X  will take the value less than or equal to x. It can be represented mathematically as below.
#
# >$F_X(x) = P(X\leq x)$
#
#
# In our case, random variable(X) is the number of hours.
#
# $ P(X\leq 2.5)$

# + colab={"base_uri": "https://localhost:8080/"} id="j6Q_wOlPlh5g" outputId="82c79ea7-ca72-4ea4-c7ad-489a2dd91760"
uniform.cdf(x = 2.5, loc = 1, scale = 3)

# + [markdown] id="C3TVqrPQlt1h"
# **b) Find the probability that a randomly selected student  requires atleast  3 hours to complete the quiz.**
#
# $ P(X>=3)$

# + colab={"base_uri": "https://localhost:8080/"} id="qy9TT_38l108" outputId="20724781-bd1f-48e3-fdcb-26eb1fc7597f"
round(1 - uniform.cdf(x = 3, loc = 1, scale = 3), 4)

# + [markdown] id="ln66mUUsmad-"
# **c) Find the probability that a randomly selected student requires 1.5 to 3.5 hours to complete the quiz.**
#
# $ P(1.5<= X <=3.5)$

# + colab={"base_uri": "https://localhost:8080/"} id="oVS-Q3f3mZlj" outputId="283b341b-1853-49d8-f3b3-63ac852902ab"
round(uniform.cdf(x = 3.5, loc = 1, scale = 3) - uniform.cdf(x = 1.5, loc = 1, scale = 3), 4) 

# + [markdown] id="xh7vsKOHVNZ8"
# # **Normal Distribution**

# + [markdown] id="yRiWnS4VabsT"
# ### **1) According to the Telecommunication Industry the average monthly cell phone bill is Rs. 850 with a standard deviation of Rs. 150. Assuming that the monthly bill follows normal distribution answer the following:**

# + [markdown] id="MJ7wKYwvVNZ_"
# **a) What is the probability that a randomly selected cell phone bill is more than Rs 1200?**

# + colab={"base_uri": "https://localhost:8080/"} id="jJ1cXSf0absV" outputId="78ae5cc4-110d-434f-a021-194964c091fc"
#To calculate this, we will calculate the cumulative probability for less than 1200 and then will subtract from 1.

round(1-stats.norm.cdf(1200,loc=850,scale=150), 4)

# + [markdown] id="1eoJzslRVNZ_"
# **b) What is the probability that a randomly selected cell phone bill is between Rs 750 and Rs 1200?**

# + colab={"base_uri": "https://localhost:8080/"} id="1uU2mRzbabsh" outputId="0d94bb46-e479-405e-cd8e-579a8e2709d9"
round(stats.norm.cdf(1200,loc=850,scale=150)-stats.norm.cdf(750,loc=850,scale=150), 4)

# + [markdown] id="tGxBocT6VNZ_"
# **c) What is the probability that a randomly selected cell phone bill is no more than Rs 650?**

# + colab={"base_uri": "https://localhost:8080/"} id="TqFcIHcUabsp" outputId="19b42148-5710-4e7d-a6db-efdc471502e8"
round(stats.norm.cdf(650,loc=850,scale=150), 4)

# + [markdown] id="oFmIG_sqVNaA"
# **d) What is the amount above which lies top 15% of cell phone bills?**

# + colab={"base_uri": "https://localhost:8080/"} id="_r55P6SNabs0" outputId="2cf77402-788c-435e-fa3a-2e7fc4c4fac8"
#Let the amount be M. P(X ≥ M) = 15% => 1 – P(X < M) = 0.85 . To calculate this we will use the percent point function i.e ppf.

round(stats.norm.ppf(0.85,loc=850,scale=150), 4)

# + [markdown] id="_lNAMUvvVNaA"
# **e) What is the amount below which lies bottom 25% of cell phone bills?**

# + colab={"base_uri": "https://localhost:8080/"} id="-7OQk_Ftabs-" outputId="c50bc6e1-8ff7-4fe0-d4c0-b6669b3209f9"
round(stats.norm.ppf(0.25,loc=850,scale=150), 4)

# + [markdown] id="QmtfulFDVNaH"
# ### **2) The mean filling capacity for a coke bottle is 500 ml with a standard deviation of 20ml. Assume that it follows a normal distribution and answer the following questions:**

# + id="ySnY5DVYVNaI"
mu = 500
sigma = 20

# + [markdown] id="ak4RyMGVVNaI"
# **a) What is the probability that the bottle filled less than 480 ml ?**

# + colab={"base_uri": "https://localhost:8080/"} id="7HZogLBGVNaI" outputId="6fd2cf8a-2bb5-4119-9143-53eea85edf15"
x1=480
z1=(x1-mu)/sigma
p=stats.norm.cdf(z1)
print ('Probaility of bottle filled less than 480 ml is %1.4f' %p)

# + [markdown] id="ILDdv_5fVNaI"
# **b) What is the probability that the bottle filled more than  520 ml?**

# + colab={"base_uri": "https://localhost:8080/"} id="u42DGuDPVNaJ" outputId="4208ece9-6c8d-4be4-d37b-3264766f66b8"
x2=520
z2=(x2-mu)/sigma
p1= 1- stats.norm.cdf(z2)
print ('probaility of bottle filled more than 520 ml is %1.4f' %p1)

# + [markdown] id="GDGLNR7dVNaJ"
# **c) What is the probability that the bottle filled between 470 ml to 525 ml?**

# + colab={"base_uri": "https://localhost:8080/"} id="_uPKpbvtVNaK" outputId="1ae86422-e645-4183-d9a5-7f1097668e0e"
x3=470
z3=(x3-mu)/sigma
x4=525
z4=(x4-mu)/sigma
p2=stats.norm.cdf(z3)
p3=stats.norm.cdf(z4)
p4=p3-p2

print ('probability that the bottle filled between 470 ml to 525 ml is %1.4f' %p4)

# + [markdown] id="7WFVLPL-VNaM"
# ### **3) In 2 Liter soft drink bottles the drink filled is normally distributed, with a mean of 2.0 liters and a standard deviation of 0.05 liter. If the bottles contain less than 95% of the listed net content(1.90 liters),  the manufacturer may be subject to penalty by the state office of consumer affairs. Bottles that have a net content above 2.1 liters may cause excess spillage upon opening. Answer the following questions:**

# + id="-1PK8VacVNaM"
mu     = 2
sigma  = 0.05

# + [markdown] id="KJh8EodMVNaM"
# **a) What is the probability that the bottle content is between 1.9 and 2.0 liters?**

# + colab={"base_uri": "https://localhost:8080/"} id="WfcWl231VNaM" outputId="5b8e470b-4b08-484f-ec17-892dbe4313ed"
Prob = stats.norm.cdf(2,loc=mu,scale=sigma) - stats.norm.cdf(1.90,loc=mu,scale=sigma)
print("Probability that the bottle content is between 1.9 and 2 liters is %3.4f" % Prob)

# + [markdown] id="hZhrsYtoVNaN"
# **b)  What is the probability that the bottle content is between 1.9 and 2.1 liters?**

# + colab={"base_uri": "https://localhost:8080/"} id="wbnjjf0aVNaN" outputId="23281c0c-f9f4-41d0-b824-3fe0a1b3445c"
Prob = stats.norm.cdf(2.1,loc=mu,scale=sigma) - stats.norm.cdf(1.9,loc=mu,scale=sigma)
print("Probability that the bottle content is between 1.9 and 2.1 liters is %3.4f" % Prob)

# + [markdown] id="H6fG71TVVNaN"
# **c)  What is the probability that the bottle content is below 1.9 liters or above 2.1 liters?**

# + colab={"base_uri": "https://localhost:8080/"} id="1Z6O0xxHVNaO" outputId="bdd5a29e-a423-4c8d-a0dc-ce46d24e37b6"
Prob1  =  stats.norm.cdf(1.9,loc=mu,scale=sigma)
Prob2  =  1 - stats.norm.cdf(2.1,loc=mu,scale=sigma)
print("Probability that the bottle content is below 1.9 liters or above 2.1 liters is  %3.4f" % (Prob1 + Prob2))

# + [markdown] id="Qc1CMY6PVNaO"
# **d) 99% of the bottles atleast have how much soft drink in them?**

# + colab={"base_uri": "https://localhost:8080/"} id="vhoVgTxBVNaO" outputId="19fe901b-e6aa-46a8-f5a5-7f65e08402a6"
Prob = stats.norm.ppf(0.01, loc = mu, scale = sigma)
print("99% of the bottles atleast have ",round(Prob,2),"Liters")

# + [markdown] id="cfuKFTnCDTeA"
# # **Sampling Distribution**

# + [markdown] id="azEQu4DoC_Q5"
# ### **Suppose an automobile battery manufacturer claims that the mean lifetime of their battery is 60 months with a standard deviation of 6 months. Suppose the distribution of battery lives of is approximately normal. Find the probability that the mean lifetime of 40 randomly sampled batteries will be less than 58 months.**

# + colab={"base_uri": "https://localhost:8080/"} id="AiWFb0LCC9Wp" outputId="6d0dd09c-a184-4aac-daba-8fd1f2ec4d3d"
# import the required function
from scipy.stats import norm
# declare the value of mean lifetime of battery in mu
mu = 60
# declare the value of standard deviation of battery in std
sigma = 6
# sample size
n = 40
# find the sample standard deviation
s = sigma/np.sqrt(40)
# find the probability
round(norm.cdf(58, loc = mu, scale = s), 4)

# + [markdown] id="BSBuNii8HHC0"
# **Insight:** The probability that the mean lifetime of 40 randomly sampled batteries will be less than 58 months is 1.75%.

# + [markdown] id="1TFwIVHqBR8O"
# # **Interval Estimation**

# + [markdown] id="hyfZcgYs_LMD"
# ### **A random sample of 40 households was selected as part of a study on electricity usage, and the number of kilowatt-hours (kWh) was recorded for each household in the sample for the March quarter of 2020. The average usage was found to be 310kWh. In a very large study in the March quarter of the previous year it was found that the standard deviation of the usage was 89kWh.**
#
# ### **Assuming the standard deviation is unchanged and that the usage is normally distributed, provide an expression for calculating a 95% confidence interval for the mean usage in the March quarter of 2019.** 
#
#

# + colab={"base_uri": "https://localhost:8080/"} id="uyAHorce_KaM" outputId="a17aca72-2c15-42a8-993f-88393ea59489"
#import the required function
from scipy.stats import norm
import numpy as np

#set the values of sample mean and sigma
x_bar, sigma = 310, 89

# set the value of sample size
n = 40

# construct the confidence interval
np.round(norm.interval(0.95, loc = x_bar, scale = sigma/np.sqrt(n)), 2)

# + [markdown] id="F1JpYY7JGGYY"
#  **Insight:** 95% of the time, the mean usage in the March quarter of 2019 will be between 282.42 and  337.58 kWh.

StarcoderdataJupyterScriptsDedupFiltered