Python Handson
Python Handson
Probability
2. import numpy as np
3. from scipy import stats
4. import statistics
5. def stats_values(arr):
6.
7. mean=round(np.mean(arr),2)
8. median=round(np.median(arr),2)
9. std_devi=round(np.std(arr),2)
10. vari=round(np.var(arr),2)
11. mode=round(stats.nstats.mode(arr),[0][0],2)
12. iqr=round(np.iqr(arr),2)
13.
14. print(mean)
15. print(median)
16. print(std_devi)
17. print(vari)
18. print(mode)
19. print(iqr)
print(round(probability, 2))
4. binomial-distribution-using-scipy-stats-package
#n=4
#p=0.60
#k=1
from scipy import stats
//P(x>=1)=1-P(x=0) this means 1.first find probability with k=0
probability=stats.binom.pmf(0,4,0.60)
//then do 1- probability
actual_probability=1-probability
print(actual_probability)
8. Chi Sqaured Test
def chi_test():
'''
Output
1. stat: Float
2. dof : Integer
3. p_val: Float
4. res: String
'''
#Note: Round off the Float values to 2 decimal places.
table=[[18,36,21,9,6],[12,36,45,36,21],[6,9,9,3,3],[3,9,9,6,3]]
stat,p_val,dof,res=chi2_contingency(table)
prob=0.95
critical=chi2.ppf(prob, dof)
alpha=1.0-prob
if p_val <= alpha:
res = 'Reject the Null Hypothesis'
else:
res = 'Failed to reject the Null Hypothesis'
stat = round(stat,2)
dof = round(dof,2)
p_val = round(p_val,2)
return stat,dof,p_val,res
if __name__=='__main__':
print(chi_test())
from itertools import permutations
comb = combinations([1, 2, 3], 2)
perm = permutations([1, 2, 3], 2)
# Print the obtained combinations
for i in list(comb):
print (i)
for i in list(perm):
print (i)
---------------------------------------------OR------------------------------------
import numpy as np
import math
def comb_perm(arr):
'''
'''
no_of_perm= len(list(permutations(arr,2)))
return no_of_comb,no_of_perm
if __name__=='__main__':
def isPalindrome(x):
# Write your doctests below.
"""
>>> isPalindrome(121)
True
>>> isPalindrome(344)
False
>>> isPalindrome(-121)
Traceback (most recent call last):
ValueError: x must be positive integer.
>>> isPalindrome("hello")
Traceback (most recent call last):
TypeError: x must be integer.
"""
# Write the functionality below
x = int(x)
temp=x
rev=0
if(x>0):
while(x>0):
dig=x%10
rev=rev*10+dig
x=x//10
if(temp==rev):
return True
else:
return False
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
x = input()
if x.isdigit():
x = int(x)
res = isPalindrome(x)
doc = inspect.getdoc(isPalindrome)
func_count = len(re.findall(r'isPalindrome', doc))
true_count = len(re.findall(r'True', doc))
false_count = len(re.findall(r'False', doc))
pp_count = len(re.findall(r'>>>', doc))
trace_count = len(re.findall(r'Traceback', doc))
fptr.write(str(res)+'\n')
fptr.write(str(func_count)+'\n')
fptr.write(str(true_count)+'\n')
fptr.write(str(false_count)+'\n')
fptr.write(str(pp_count) + '\n')
fptr.write(str(trace_count) + '\n')
fptr.close()
import inspect
import re
import unittest
import math
class Circle:
def __init__(self, radius):
# Define the initialization method below
self.radius=radius
if not isinstance(self.radius,(int,float)):
raise TypeError("radius must be a number")
elif(self.radius>1000 or self.radius<0):
raise ValueError("radius must be between 0 and 1000 inclusive")
else:
pass
def area(self):
# Define the area functionality below
return math.pi*(self.radius**2)
def circumference(self):
return 2*math.pi*self.radius
# Define the circumference functionality below
class TestCircleCreation(unittest.TestCase):
def test_creating_circle_with_numeric_radius(self):
# Define a circle 'c1' with radius 2.5 and check if
# the value of c1.radius equal to 2.5 or not
c1=Circle(2.5)
self.assertEqual(c1.radius,2.5)
def test_creating_circle_with_negative_radius(self):
# Try Defining a circle 'c' with radius -2.5 and see
# if it raises a ValueError with the message
# "radius must be between 0 and 1000 inclusive"
with self.assertRaises(ValueError) as e:
c=Circle(-2.5)
self.assertEqual(str(e.exception),"radius must be between 0 and 1000 inclusive")
def test_creating_circle_with_greaterthan_radius(self):
# Try Defining a circle 'c' with radius 1000.1 and see
# if it raises a ValueError with the message
# "radius must be between 0 and 1000 inclusive"
with self.assertRaises(ValueError) as e:
c=Circle(1000.1)
self.assertEqual(str(e.exception),"radius must be between 0 and 1000 inclusive")
def test_creating_circle_with_nonnumeric_radius(self):
# Try Defining a circle 'c' with radius 'hello' and see
# if it raises a TypeError with the message
# "radius must be a number"
with self.assertRaises(TypeError) as e:
c=Circle("hello")
self.assertEqual(str(e.exception),"radius must be a number")
if __name__ == '__main__':
fptr = open('output.txt', 'w')
runner = unittest.TextTestRunner(fptr)
unittest.main(testRunner=runner, exit=False)
fptr.close()
pass_count = pass_count[0]
print(str(pass_count))
doc1 = inspect.getsource(TestCircleCreation.test_creating_circle_with_numeric_radius)
doc2 = inspect.getsource(TestCircleCreation.test_creating_circle_with_negative_radius)
doc3 = inspect.getsource(TestCircleCreation.test_creating_circle_with_greaterthan_radius)
doc4 = inspect.getsource(TestCircleCreation.test_creating_circle_with_nonnumeric_radius)
import inspect
import doctest
import re
import math
# Define the class 'Circle' and its methods with proper doctests:
class Circle:
def __init__(self, radius):
# Define doctests for __init__ method:
"""
>>> c1 = Circle(2.5)
>>> c1.radius
2.5
"""
self.radius = radius
def area(self):
# Define doctests for area method:
"""
>>> c1 =Circle(2.5)
>>> c1.area()
19.63
"""
return round(math.pi*(self.radius**2),2)
# Define area functionality:
def circumference(self):
# Define doctests for circumference method:
"""
>>> c1=Circle(2.5)
>>> c1.circumference()
15.71
"""
return round(math.pi* (self.radius*2),2)
# Define circumference functionality:
if __name__ == '__main__':
print Greeting Quote
import math
import os
import random
import re
import sys
#
# Complete the 'Greet' function below.
#
# The function accepts STRING Name as parameter.
#
def Greet(Name):
# Write your code here
print(f'Welcome {Name}.')
print('It is our pleasure inviting you.')
print('Have a wonderful day.')
if __name__ == '__main__':
Name = input()
Greet(Name)
#Name spaces
import math
import os
import random
import re
import sys
#
# Complete the 'Assign' function below.
#
# The function accepts following parameters:
# 1. INTEGER i
# 2. FLOAT f
# 3. STRING s
# 4. BOOLEAN b
#
def Assign(i, f, s, b):
# Write your code here
w = i
x = f
y = s
z = b
print(w)
print(x)
print(y)
print(z)
print(dir())
if __name__ == '__main__':
i = int(input().strip())
f = float(input().strip())
s = input()
b = input().strip()
Assign(i, f, s, b)
import math
import os
import random
import re
import sys
#
# Complete the 'docstring' function below.
#
# The function is expected to output a STRING.
# The function accepts STRING x as a parameter.
#
def docstring(functionname):
# Write your code here
return help(functionname)
if __name__ == '__main__':
x = input()
docstring(x)
#Namespaces 2
import math
import os
import random
import re
import sys
#
# Complete the 'Prompt' function below.
#
#
def Prompt():
# Write your code here
print( 'Enter a STRING:')
x =''
print(input(x))
print(type(x))
if __name__ == '__main__':
Prompt()
#Range 1
import math
import os
import random
import re
import sys
#
# Complete the 'func' function below.
#
# The function is expected to print an INTEGER.
# The function accepts following parameters:
# 1. INTEGER startvalue
# 2. INTEGER endvalue
# 3. INTEGER stepvalue
#
def rangefunction(startvalue, endvalue, stepvalue):
# Write your code here
a = []
for i in range(startvalue,endvalue,stepvalue):
a.append(i**2)
print(*a, sep ='\t')
if __name__ == '__main__':
x = int(input().strip())
y = int(input().strip())
z = int(input().strip())
rangefunction(x, y, z)
#Usage imports
import math
import os
import random
import re
import sys
#
# Complete the 'calc' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER c as parameter.
#
def calc(c):
# Write your code here
from math import pi
# calculate radius of the circle
r = (c/(2*pi))
area = (pi * r**2)
r = round(r,2)
area = round(area,2)
return (r,area)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
c = int(input().strip())
result = calc(c)
fptr.write(str(result) + '\n')
fptr.close()
# Using int
import math
import os
import random
import re
import sys
#
# Complete the 'Integer_fun' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. FLOAT a
# 2. STRING b
#
def Integer_fun(a, b):
# Write your code here
c = int(a)
d = int(b)
print(type(a))
print(type(b))
print(c)
print(d)
print(type(c))
print(type(d))
if __name__ == '__main__':
a = float(input().strip())
b = input()
Integer_fun(a, b)
import math
import os
import random
import re
import sys
#
# Complete the 'find' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER num1
# 2. INTEGER num2
# 3. INTEGER num3
#
def find(num1, num2, num3):
# Write your code here
print(num1<num2 and num2>= num3,num1>num2 and num2<= num3,num3==num1 and
num1!= num2)
if __name__ == '__main__':
num1 = int(input().strip())
num2 = int(input().strip())
num3 = int(input().strip())
def fibonacci(n):
x, y = 0, 1
for _ in range(n):
yield x
x, y = y, x + y
def fib_sum(n):
return sum(fibonacci(n))
num = int(input())
print(fib_sum(num))
def tetrahedral_gen(lower, upper):
val = lower # Value used as layer number
end = upper + 1
while val < end:
# The Formula for Next Number
yield int(val * (val + 1) * (val + 2) / 6)
val += 1 # Increment Layer Number
values = tetrahedral_gen(1,7)
print(list(values))
# python dictionary
import math
import os
import random
import re
import sys
# 1. STRING key1
# 2. STRING value1
# 3. STRING key2
# 4. STRING value2
# 5. STRING value3
# 6. STRING key3
x={key1:value1}
print(x)
x1={key2: value2}
x.update(x1)
print(x)
x2={key1:value3}
x.update(x2)
print(x)
x.pop(key3)
return x
# z=x.update({"key3": "value3"})
# print(z)
# return {key3:value3}
if __name__ == '__main__':
key1 = input()
value1 = input()
key2 = input()
value2 = input()
value3 = input()
key3 = input()