You are on page 1of 48

Name- Shriya Manuja

Batch- 2023-25
Section- A (North Campus)
Roll No.- 23236761049
College- Department of Operational Research
Python Practical File

1
Table of Contents

Practica Objective Page


l Number
Number
1 Write a program to enter name and display as “Hello, Name”. 4
2 Write a menu driven program to enter two numbers and print the 5,6
arithmetic operations.
3 To compute roots of a quadratic equation 7
4 Write a menu driven program to reverse the digits and sum of the 8
given number
5 Write a menu driven program to enter a number whether number 9
is odd or even or prime.
6 WAP to find maximum out of entered 3 numbers 10
7 Write a program to display ASCII code of a character and vice 11
versa.
8 Write a program to check if the entered number is Armstrong or 12
not.
9 Write a Program to find factorial of the entered number using 13
recursion.
10 Write a Program to enter the number of terms and to print the 14
Fibonacci Series.
11 Write a Program to enter the numbers and to print greatest 15
number using loop.
12 Write a Program to enter the string and to check if it’s palindrome 16
or not using loop
13 Program to enter the 5 subjects’ numbers and print the grades 17,18
A/B/C/D/E.
14 Write a program in python language to display the given pattern. 19
15 Write a python function sin(x,n) to calculate the value of sin(x) 20
using its Taylor series expansion up to n terms.
16 WAP to determine EOQ using various inventory models 21
17 Write a Program to determine different characteristics using 27
various Queuing models
18 Write a Program to implement Inheritance. Create a class 30
Employee inherit two classes Manager and Clerk from Employee.
19 Program to fit Poisson distribution on a given data. 31
20 Write a program to implement linear regression using python. 32
21 Write a program to perform read and write operation with .csv file. 34

22 Write a Program to enter multiple values-based data in multiple 35


columns/rows and show that data in python using DataFrames
and
pandas.
23 WAP in python to perform various statistical measures using 36
pandas.
24 Write a program to plot a bar chart in python to display the result 37
of a school for five consecutive years.
25 Write a program in python to plot a graph for the function y = x2 38

2
26 Write a program in python to plot a pie chart on consumption of 39
water in daily life.
27 WAP to find whether a year is leap year or not 40

28 WAP to compute BMI 41

29 WAP to imitate treasure hunt game 42

30 WAP to generate bill from pizza shop depending on user 44


preference from small,medium, large. Extra topping charge is
separate and extra charge for cheese burst addition
31 Wap to play stone, paper, scissors with computer 46

32 WAP that inputs the no. of characters for your password,then it 48


asks for the no of letters,no of numeric figures, no of special
characters to be included. Then the computer will generate a
random password(system generated) for the inputs taken shuffled

3
Practical 1
'''
Name: Shriya Manuja
Section: A
Batch:2023-25

Title- WAP to enter Name and display "Hello, Name"

Code of the Program

name = input("Please enter your name: ")


print("Hello " + name + "!")

Output of the Program

Please enter your name: Shriya


Hello Shriya!

Practical-1b

Title- (ii) WAP to generate hashtag by taking two inputs -


Name of Food and Name of Place it belongs to or Name of Famous Monument and
Country

Code of the Program

Male_Lead = input("Enter the male lead name: ")


Female_Lead = input("Enter the female lead name: ")
print("#"+ Male_Lead[0:3]+Female_Lead[0:3])

Output of the Program

Enter the male lead name: Raj


Enter the female lead name: Simran
#RajSim

Practical-1c

Title- WAP to take a review from user and display the character count of the
review

Code of the program

sentence = input("Please enter the sentence: ")


print(len(sentence))

Output of the program

Please enter the sentence: Happiness can be found, even in the darkest of times,
if one only remembers to turn on the light.
97

4
Practical 2
'''
Name: Shriya Manuja
Section: A
Batch :2023-25
Practical 2: Write a menu driven program to enter two numbers and print the arithmetic operations
'''

num1=float(input("Enter First Number: "))


num2=float(input("Enter Second Number: "))
action=input("Enter the arithmetic operation you want to perform
(+,-,*,/,//,%,**): ")
if action=="+":
sum=num1+num2
print("Sum of the numbers you entered is",sum)
elif action=="-":
diff=num1-num2
print("Difference of the numbers you entered is",diff)
elif action=="*":
prod=num1*num2
print("Product of the numbers you entered is",prod)
elif action=="/":
div=num1/num2
print("Division of the numbers you entered is",div)
elif action=="//":
fdiv=num1//num2
print("Floor Division of the numbers you entered is",fdiv)
elif action=="%":
rem=num1%num2
print("Remainder after division of the numbers you entered
is",rem)
elif action=="**":
exp=num1**num2
print(num1,"raised to the power",num2,"is",exp)
else:
print("Enter a valid operator!")

'''
OUTPUT CASE 1
Enter First Number: 1
Enter Second Number: 2
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): +
Sum of the numbers you entered is 3.0

OUTPUT CASE 2
Enter First Number: 1
Enter Second Number: 2
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): -
Difference of the numbers you entered is -1

OUTPUT CASE 3
Enter First Number: 1

5
Enter Second Number: 2
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): *
Product of the numbers you entered is 2.0

OUTPUT CASE 4
Enter First Number: 1
Enter Second Number: 2
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): /
Division of the numbers you entered is 0.5

OUTPUT CASE 5
Enter First Number: 2.5
Enter Second Number: 1
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): //
Floor Division of the numbers you entered is 2.0

OUTPUT CASE 6
Enter First Number: 10
Enter Second Number: 3
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): %
Remainder after division of the numbers you entered is 1.0

OUTPUT CASE 7
Enter First Number: 5
Enter Second Number: 2
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): **
5.0 raised to the power 2.0 is 25.0

OUTPUT CASE 8
Enter First Number: 12
Enter Second Number: 43
Enter the arithmetic operation you want to perform (+,-,*,/,//,%,**): ^
Enter a valid operator!

‘’’

6
Practical 3
'''
Name: Shriya Manuja
Section: A
Batch: 2023-25
Practical 3: To compute roots of a quadratic equation
'''
Title- WAP to compute roots of a quadratic equation

Code of the Program-

import math
import cmath
a= input("Please enter a: ")
b= input("Please enter b: ")
c= input("Please enter c: ")
print("Your quadratic equation is (" + a+")x^2" + " + (" + b + ")x"+ " + ("
+c+")")
D = int(b)**2- 4* int(a)*int(c)
print("The discriminant is " + str(D))
if D > 0:
root_1 = (-int(b)+math.sqrt(D))/(2*int(a))
root_2 = (-int(b)-math.sqrt(D))/(2*int(a))
print("The roots are real and distinct " + str(root_1) +", "+ str(root_2))
elif D == 0:
root_3 = (-int(b)+sqrt(D))/(2*int(a))
print("The roots are real and equal " + str(root_3))
elif D <0:
root_4 = (-int(b)+cmath.sqrt(D))/(2*int(a))
root_5 = (-int(b)-cmath.sqrt(D))/(2*int(a))
print("The roots are complex and distinct " + str(root_4) +", "+
str(root_5))

Output of the program-

Please enter a: 2
Please enter b: 4
Please enter c: 1
Your quadratic equation is (2)x^2 + (4)x + (1)
The discriminant is 8
The roots are real and distinct -0.2928932188134524, -1.7071067811865475

7
Practical 4
'''
Name: Shriya Manuja
Section: A
Batch: 2023-25
Practical 4: Write a menu driven program to reverse the digits and sum of the given number
'''
print("1. for reverse" )
print("2. For sum" )
choice=int(input("enter choice "))
n=int(input("Enter number "))
if choice==1:
rem=0
sum=0
temp=n
while(temp>0):
a=temp%10
temp=temp//10
rem=rem*10+a
print("Reverse",rem)
else:
sum=0
temp=n
while(temp>0):
a=temp%10
temp=temp//10
sum=sum+a
print("sum",sum)
'''
Output 1
1. for reverse
2. For sum
enter choice 1
Enter number 248
sum 14
Output 2
1. for reverse
2. For sum
enter choice 1
Enter number 378
Reverse 873
'''

8
Practical 5
'''
Name: Shriya Manuja
Section :A
Batch : 2023-25
Practical 5: Write a menu driven program to enter a number whether number is odd or even or
prime
'''

n=int(input("Enter a number "))


print("1. for odd even")
print("2. for prime")
choice=int(input("Enter your choice "))
if choice==1:
if n%2==0:
print("Even")
else:
print("odd")
elif choice==2:
for i in (2,n-1):
if n%i==0:
print("not prime")
else:
print("prime")
break

'''
OUTPUT 1
Enter a number 14
1. for odd even
2. for prime
Enter your choice 2
not prime
OUTPUT 2
Enter a number 17
1. for odd even
2. for prime
Enter your choice 1
odd
'''

9
Practical 6
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 6: WAP to find maximum out of entered 3 numbers
'''

a=int(input("enter number "))


b=int(input("enter number "))
c=int(input("enter number "))
if (a>b and a>c):
print(f"{a} is largest")
elif(b>=c and b>=a):
print(f"{b} is largest")
else:
print(f"{c} is largest")
‘’’
OUTPUT
enter number 7
enter number 2
enter number 13
13 is largest
‘’’

10
Practical 7
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 7: Write a program to display ASCII code of a character and vice versa.
'''
def display_ascii(user_input):
user_input = str(user_input)
for i in user_input:
print(f"ASCII code for {i} is {ord(i)}")

def decode_ascii(ascii_code):
print(f"The character value of {ascii_code} ASCII value is:
{chr(ascii_code)}")

user_input = input("Enter your character for ASCII value : ")


display_ascii(user_input=user_input)
user_ascii_input = int(input("Enter your ASCII value for character :
"))
decode_ascii(user_ascii_input)

‘’’
OUTPUT
Enter your character for ASCII value : Hello
ASCII code for o is 111
ASCII code for e is 101
ASCII code for H is 72
ASCII code for l is 108
Enter your ASCII value for character : 101
The character value of 72 ASCII value is: e
‘’’

11
Practical 8
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 8: Write a program to check if the entered number is Armstrong or not.
'''
def armStrongNumber(user_input):
user_input = str(user_input)
expo = len(user_input)
sum=0
for i in user_input:
sum+=(int(i)**expo)
if(sum == int(user_input)):
print("Given Number is ArmStrong Number")
else:
print("Given Number is not Armstrong Number")

num = int(input("Enter your number : "))


armStrongNumber(num)

'''
OUTPUT
Enter your number : 346
Given Number is not ArmStrong Number

Enter your number : 153


Given Number is Armstrong Number '''

12
Practical 9
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 9: Write a program in python language to find factorial of the entered number using
recursion.
‘’’
def factorial(n):
if (n==1 or n==0):

return 1

else:

return (n * factorial(n - 1))


num = int(input("Enter the number : "))
print(num,"! =",factorial(num))
‘’’
OUTPUT
Enter the number : 4

4 ! = 24

'''

13
Practical 10
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25

Practical 10: Write a program in python language to enter the number of terms and to print the
Fibonacci series.
‘’’

def fibonacci(n):
if n == 1:
return 0
if n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

l = int(input("Input the number of fibonacci terms : "))

for i in range(1,l+1):
print(fibonacci(i), end = " ")

‘’’

OUTPUT
Input the number of fibonacci terms : 7
0 1 1 2 3 5 8
'''

14
Practical 11
'''
Name : Shriya Manuja
Section A
Batch: 2023-25
Practical 11: Write a Program to enter the numbers and to print greatest number using loop.
'''
lar_num= int(input ("enter a number initially : "))
check_num= input ("enter a number to check wether it is largest or
not : ")
while check_num != "Done" :
if lar_num > int(check_num):
print(f"The largest number is {lar_num}")
else :
lar_num= int(check_num)
print(f"The largest number is {lar_num} ")
check_num= input ("enter a number to check wether it is largest or
not : ")

'''
OUTPUT
enter a number initially : 5
enter a number to check wether it is largest or not : 2
The largest number is 5
enter a number to check wether it is largest or not : 7
The largest number is 7
enter a number to check wether it is largest or not : 6
The largest number is 7
enter a number to check wether it is largest or not : Done
'''

15
Practical 12
'''
Name : Shriya Manuja
Section A
Batch: 2023-25
Practical 12: Write a Program to enter the string and to check if it’s palindrome or not using loop.
'''

string = input("Enter string : ")

rev_str = ""

for i in string:
rev_str = i + rev_str

print("Reversed string : ", rev_str)

if(string == rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

'''
OUTPUT CASE 1
Enter string : string
Reversed string : gnirts
The string is not a palindrome.

OUTPUT CASE 2
Enter string : madam
Reversed string : madam
The string is a palindrome.
'''

16
Practical 13
'''
Name : Shriya Manuja
Section A
Batch: 2023-25
Practical 13: Write a Program to enter the 5 subjects’ numbers and print the grades A/B/C/D/E.
'''

def grade_alot(s):
if s <0 or s>100:
print("Wrong Input")
elif s>90:
print("Grade A")
elif s>80:
print("Grade B")
elif s>70:
print("Grade C")
elif s>60:
print("Grade D")
else:
print("Grade E")

e=int(input("Enter English marks: "))


h=int(input("Enter Hindi marks: "))
m=int(input("Enter Mathematics marks: "))
p=int(input("Enter Physics marks: "))
c=int(input("Enter Chemistry marks: "))
a=(e+h+m+p+c)/5
9

print(f"The marks in English is {e} and thus grade is: ")


grade_alot(e)
print(f"The marks in Hindi is {h} and thus grade is: ")
grade_alot(h)
print(f"The marks in Mathematics is {m} and thus grade is: ")
grade_alot(m)
print(f"The marks in Physics is {p} and thus grade is:")
grade_alot(p)
print(f"The marks in Chemistry is {c} and thus grade is :")
grade_alot(c)
print(f"The Averages marks is {a} and thus average grade is: ")
grade_alot(a)

'''
OUTPUT
Enter English marks: 65
Enter Hindi marks: 72
Enter Mathematics marks: 85
Enter Physics marks: 90
Enter Chemistry marks: 73
The marks in English is 65 and thus grade is:
Grade D

17
The marks in Hindi is 72 and thus grade is:
Grade C
The marks in Mathematics is 85 and thus grade is:
Grade B
The marks in Physics is 92 and thus grade is:
Grade A
The marks in Chemistry is 73 and thus grade is :
Grade C
The Averages marks is 75.0 and thus average grade is:
Grade C
'''

18
Practical 14
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 14: Write a program in python language to display the given pattern
'''
n=int(input("Enter rows needed "))
for i in range(n):
for j in range(n-i-1):
print(" ", end=" ")
for j in range(i,-1,-1):
print(n-j,end=" ")
print()
'''
OUTPUT
Enter rows needed 5
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5

Enter rows needed 6


6
5 6
4 5 6
3 4 5 6
2 3 4 5 6
1 2 3 4 5 6
'''

19
Practical 15
'''
Name : Shriya Manuja
Section A
Batch: 2023-25
Practical 15: Write a python function sin(x,n) to calculate the value of sin(x) using its Taylor series
expansion up to n terms.
'''
x=int(input("Enter the degree: "))
n=int(input("Enter the number of terms: "))

def sin():
r=x*22/7*180
result=0
numerator = r
denominator= 1
for i in range (1, n+1):
single_term= numerator/denominator
result+= single_term
numerator = -numerator*r*r
denominator= denominator*(2*i)*(2*i+1)
return result
def main():
result= sin()
print(f"The value of sin({x}) is {result} ")
main()

'''
OUTPUT
Enter the degree: 0
Enter the number of terms: 10
The value of sin(0) is 0.0
'''

20
Practical 16
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 16: WAP to determine EOQ using various inventory models.
'''

import math

def eoq():
print("EOQ Model Initiated...")
y=float(input("Enter Annual Demand: "))
a=float(input("Enter Ordering Cost per order: "))
ic=(input("For Inventory Carrying/Holding Cost\nDo you want to
enter Cost or Percentage?
")).lower()
if ic=='cost':
h=float(input("Enter Inventory Carrying/Holding Cost per
year: "))
elif ic=='percentage':
c=float(input("Enter Unit Cost of the item: "))
i=float(input("Enter Percentage of Unit Cost, taken into
consideration for
Carrying/Holding Cost: "))
h=i*c/100
else:
print("Invalid Choice!")

eoq=math.sqrt((2*y*a)/h)
print(f"The Economic Order Quantity using the EOQ Model is {eoq}
units.")

def epq():
print("EPQ ModelInitiated...")
y=float(input("Enter Annual Demand: "))
s=float(input("Enter Annual Production: "))
assert y<s, "Production shall be more than the Demand."
a=float(input("Enter Setup Cost per order: "))
ic=(input("For Inventory Carrying/Holding Cost\nDo you want to
enter Cost or Percentage?
")).lower()
if ic=='cost':
h=float(input("Enter Inventory Carrying/Holding Cost per
year: "))
elif ic=='percentage':
c=float(input("Enter Unit Production Cost of the item: "))
i=float(input("Enter Percentage of Unit Cost, taken into
consideration for
Carrying/Holding Cost: "))
h=i*c/100
else:
print("Invalid Choice!")

factor=s/(s-y)
epq=math.sqrt((2*y*a*factor)/h)
print(f"The Economic Order Quantity using the EPQ Model is {epq}
units.")

def backorders():
print("Backorders Model With Planned Shortages EOQ
Initiated. .. ")
y=float(input("Enter Annual Demand: "))
a=float(input("Enter Ordering/Setup Cost per order: "))
pi=float(input("Enter Backorder Cost per unit per year: "))
ic=(input("For Inventory Carrying/Holding Cost\nDo you want to
enter Cost or Percentage?
")).lower()

if ic=='cost':
h=float(input("Enter Inventory Carrying/Holding Cost per
year: "))
elif ic=='percentage':
c=float(input("Enter Unit Cost of the item: "))
i=float(input("Enter Percentage of Unit Cost, taken into
consideration for
Carrying/Holding Cost: "))
h=i*c/100
else:

22
print("Invalid Choice!")

factor=(h+pi)/pi
q=math.sqrt((2*y*a*factor)/h)
s=(h/(h+pi))*q
print(f"The Economic Order Quantity using the EOQ with
Backorders Model (planned
shortages) is {q}units.")

print(f"The Maximum number of Backorders can be {s} units.")

def finsupply():
print("EOQ with Finite Supply Model Initiated...")
y=float(input("Enter Annual Demand: "))
a=float(input("Enter Ordering/Setup Cost per order: "))
s=float(input("Enter Annual Supply/Production: "))
ic=(input("For Inventory Carrying/Holding Cost\nDo you want to
enter Cost or Percentage? ")).lower()
if ic=='cost':
h=float(input("Enter Inventory Carrying/Holding Cost per
year: "))
elif ic=='percentage':
c=float(input("Enter Unit Cost of the item: "))
i=float(input("Enter Percentage of Unit Cost, taken into
consideration for
Carrying/Holding Cost: "))
h=i*c/100
else:
print("Invalid Choice!")

factor=math.sqrt(s/(s-y))
q=factor*math.sqrt((2*y*a)/h)
print(f"The Economic Order Quantity using the EOQ with Finite
Supply Model is {q} units.")

def main():
print("Hello \n KIndly enter the Model No. of the model you want
to use")
print("MODEL 1: EOQ\nMODEL 2: EPQ\nMODEL 3: EOQ with Backorders
(planned shortages\nMODEL
4: EOQ with Finite Supply)")

23
choice=input("Enter your choice: ")
if choice=='1':
eoq()
if choice=='2':
epq()
if choice=='3':
backorders()
if choice=='4':
finsupply()

if name == " main ":


main()# Example usage

'''
OUTPUT CASE 1
Hello kindly enter the Model No. of the model you want to use
MODEL 1: EOQ
MODEL 2: EPQ
MODEL 3: EOQ with Backorders (planned shortages
MODEL 4: EOQ with Finite Supply)
Enter your choice: 1
EOQ Model Initiated...
Enter Annual Demand: 1200
Enter Ordering Cost per order: 200
For Inventory Carrying/Holding Cost
Do you want to enter Cost or Percentage? Cost
Enter Inventory Carrying/Holding Cost per year: 1
The Economic Order Quantity using the EOQ Model is 692.8203230275509 units.

OUTPUT CASE 2
Hello kindly enter the Model No. of the model you want to use
MODEL 1: EOQ
MODEL 2: EPQ
MODEL 3: EOQ with Backorders (planned shortages
MODEL 4: EOQ with Finite Supply)
Enter your choice: 2
EPQ Model Initiated...
Enter Annual Demand: 1200

24
Enter Annual Production: 1400
Enter Setup Cost per order: 200
For Inventory Carrying/Holding Cost
Do you want to enter Cost or Percentage? Cost
Enter Inventory Carrying/Holding Cost per year: 2
The Economic Order Quantity using the EPQ Model is 1296.148139681572 units.

OUTPUT CASE 3
Hello kindly enter the Model No. of the model you want to use
MODEL 1: EOQ
MODEL 2: EPQ
MODEL 3: EOQ with Backorders (planned shortages
MODEL 4: EOQ with Finite Supply)
Enter your choice: 3
Backorders Model with Planned Shortages EOQ Initiated....
Enter Annual Demand: 1200
Enter Ordering/Setup Cost per order: 200
Enter Backorder Cost per unit per year: 30
For Inventory Carrying/Holding Cost
Do you want to enter Cost or Percentage? Cost
Enter Inventory Carrying/Holding Cost per year: 7
The Economic Order Quantity using the EOQ with Backorders Model (planned shortages) is
290.81167199998794units.
The Maximum number of Backorders can be 55.01842443243015 units.

OUTPUT CASE 4
Hello kindly enter the Model No. of the model you want to use
MODEL 1: EOQ
MODEL 2: EPQ
MODEL 3: EOQ with Backorders (planned shortages
MODEL 4: EOQ with Finite Supply)
Enter your choice: 4
EOQ with Finite Supply Model Initiated...
Enter Annual Demand: 1200
Enter Ordering/Setup Cost per order: 200
Enter Annual Supply/Production: 1400
For Inventory Carrying/Holding Cost

25
Do you want to enter Cost or Percentage? Percentage
Enter Unit Cost of the item: 15
Enter Percentage of Unit Cost, taken into consideration for Carrying/Holding Cost: 20
The Economic Order Quantity using the EOQ with Finite Supply Model is 1058.3005244258363
units.'''

26
Practical 17
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 17: Programme to determine different characteristics using various Queuing models.
'''

import math

def M_M_1(lambd, mu):


rho = lambd/mu
Lq = rho**2/(1-rho)
L = Lq + rho
Wq = Lq/lambd
W = Wq + 1/mu
print("M/M/1 Model:")
print("Expected number of customers in the queue (Lq): ", Lq)
print("Expected number of customers in the system (L): ", L)
print("Expected time in the queue (Wq): ", Wq)
print("Expected time in the system (W): ", W)
print()

def M_M_c(lambd, mu, c):


rho = lambd/(c*mu)
P01 = sum([(c*rho)**n/math.factorial(n) for n in range(c+1)])
P02= ((c*rho)**c)/(math.factorial(c)*(1-rho))
P0 = P01+P02
P0=1/P0
Lq = (((c*rho)**c) * rho*P0)/(math.factorial(c) * (1-rho)**2)
L = Lq + lambd/mu
Wq = Lq/lambd
W = Wq + 1/mu
print("M/M/c Model:")
print("Expected number of customers in the queue (Lq): ", Lq)
print("Expected number of customers in the system (L): ", L)
print("Expected time in the queue (Wq): ", Wq)
print("Expected time in the system (W): ", W)

27
print()

def M_M_1_K(lambd, mu, K):


rho = (lambd/mu)
if rho == 1:
Lq = (K*(K-1))/(2*(K+1))
else:
Lq = (rho/(1-rho))-(rho*(K*(rho**K))+1)/(1-(rho**(K+1)))
L = Lq + rho
Wq = Lq/lambd
W = Wq + 1/mu
print("M/M/1/K Model:")
print("Expected number of customers in the queue (Lq): ", Lq)
print("Expected number of customers in the system (L): ", L)
print("Expected time in the queue (Wq): ", Wq)
print("Expected time in the system (W): ", W)
print()

# Example usage:
M_M_1(2, 3)
M_M_c(2, 3, 5)
M_M_1_K(2 ,3, 4)

'''
OUTPUT

M/M/1 Model:
Expected number of customers in the queue (Lq): 1.333333333333333
Expected number of customers in the system (L): 1.9999999999999996
Expected time in the queue (Wq): 0.6666666666666665
Expected time in the system (W): 0.9999999999999998

M/M/c Model:
Expected number of customers in the queue (Lq): 9.995743479235089e-05
Expected number of customers in the system (L): 0.6667666241014589
Expected time in the queue (Wq): 4.9978717396175446e-05

28
Expected time in the system (W): 0.33338331205072946

M/M/1/K Model:
Expected number of customers in the queue (Lq): 0.24170616113744092
Expected number of customers in the system (L): 0.9083728278041076
Expected time in the queue (Wq): 0.12085308056872046
Expected time in the system (W): 0.4541864139020538
'''

29
Practical 18
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 18: WAP to implement Inheritance. Create a class Employee inherit two classes Manager
and Clerk from Employee.
'''
class Employee:

def init (self, name, emp_id, salary):

self.name = name

self.emp_id = emp_id

self.salary = salary

def display_employee_details(self):

print(f"Employee Name: {self.name}")

print(f"Employee ID: {self.emp_id}")

print(f"Salary: {self.salary}")

class Manager(Employee):

def init (self, name, emp_id, salary, department):

super(). init (name, emp_id, salary)

self.department = department

def display_manager_details(self):

self.display_employee_details()

print(f"Department: {self.department}")

class Clerk(Employee):

def init (self, name, emp_id, salary, shift):

super(). init (name, emp_id, salary)

self.shift = shift

def display_clerk_details(self):

30
self.display_employee_details()

print(f"Shift: {self.shift}

# Creating objects of Manager and Clerk manager1

= Manager("John", 1001, 50000, "Sales")

clerk1 = Clerk("Jane", 1002, 25000, "Night Shift")

# Calling methods of Manager and Clerk

manager1.display_manager_details()

print("\n")

clerk1.display_clerk_details()

'''

OUTPUT
Employee Name: John
Employee ID: 1001
Salary: 50000
Department: Sales

Employee Name: Jane


Employee ID: 1002
Salary: 25000
Shift: Night Shift

31
Practical-19
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 19: WAP to fit Poisson Distribution to given data
‘’’

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.special import factorial
def poisson(k, lamb, scale):
return scale*(lamb**k/factorial(k))*np.exp(-lamb)
np.random.seed(42)
data = np.random.poisson(5,100)
fig, ax = plt.subplots()
ax.hist(data,bins=10,alpha=0.3)
y,x=np.histogram(data,bins=10)
x = x + (x[1]-x[0])/2
x = np.delete(x,-1)
parameters, cov_matrix = curve_fit(poisson, x, y, p0=[2., 2.])
x_new = np.linspace(x[1], x[-1], 50)
ax.plot(x_new, poisson(x_new, *parameters), color='b')
'''
Output

‘’’

32
Practical 20
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 20: WAP to implement Linear Regression using Python.

‘’’
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

x = 30 * np.random.random((20, 1))

y = 0.5 * x + 1.0 + np.random.normal(size=x.shape)

model = LinearRegression()
model.fit(x, y)

x_new = np.linspace(0, 30, 100)


y_new = model.predict(x_new[:, np.newaxis])

plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter(x, y)
ax.plot(x_new, y_new)

ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()

'''
Output

‘’’

33
Practical 21
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 21: WAP to perform read and write operations in Python with csv files.
‘’’

import pandas as pd
#reading a csv filen
df = pd.read_csv('iris.csv')
print(df)

'''
Output
sepal.length sepal.width petal.length petal.width variety
0 5.1 3.5 1.4 0.2 Setosa
1 4.9 3.0 1.4 0.2 Setosa
2 4.7 3.2 1.3 0.2 Setosa
3 4.6 3.1 1.5 0.2 Setosa
4 5.0 3.6 1.4 0.2 Setosa
.. ... ... ... ... ...
145 6.7 3.0 5.2 2.3 Virginica
146 6.3 2.5 5.0 1.9 Virginica
147 6.5 3.0 5.2 2.0 Virginica
148 6.2 3.4 5.4 2.3 Virginica
149 5.9 3.0 5.1 1.8 Virginica

[150 rows x 5 columns]


‘’’

34
Practical 22
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 22: WAP to enter multiple values-based data in multiple columns/rows and show that data
in python using DataFrames and pandas.
‘’’

import pandas as pd
students = [['Jack Ma', 34, 'Sydney', 'Australia'],
['Ritika', 30, 'Delhi', 'India'],
['Vansh', 31, 'Delhi', 'India'],
['Nany', 32, 'Tokyo', 'Japan'],
['May', 16, 'New York', 'US'],
['Michael', 17, 'Las Vegas', 'US']]

#creating a data frame of students using pandas


data_new = pd.DataFrame(students,
columns=['Name', 'Age', 'City', 'Country'],
index=['0', '1', '2', '3', '4', '5'])

print(data_new)

'''
Output
Name Age City Country
0 jackma 34 Sydeny Australia
1 Ritika 30 Delhi India
2 Vansh 31 Delhi India
3 Nany 32 Tokyo Japan
4 May 16 New York US
5 Michael 17 las vegas US

‘’’

35
Practical 23
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 23: WAP in python to perform various statistical measures using pandas.
‘’’

import numpy as np
import pandas as pd
mydata = np.random.randn(9).reshape(3,3)
mydata = pd.DataFrame(mydata, columns = ["a","b","c"])
print(mydata)
print(mydata.describe())
'''
Output
a b c
0 0.543080 -0.119660 -0.236676
1 -0.462042 0.921270 -0.394241
2 0.481430 -1.326521 -1.461620
a b c
count 3.000000 3.000000 3.000000
mean 0.187490 -0.174970 -0.697512
std 0.563354 1.124916 0.666410
min -0.462042 -1.326521 -1.461620
25% 0.009694 -0.723090 -0.927930
50% 0.481430 -0.119660 -0.394241
75% 0.512255 0.400805 -0.315458
max 0.543080 0.921270 -0.236676
‘’’

36
Practical 24
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 24: WAP to plot a bar chart in python to display the result of a school for five consecutive
years.
‘’’

import numpy as np
import matplotlib.pyplot as plt

# creating the dataset


data = {'2016':72, '2017':70, '2018':69,
'2019':78, '2020': 81}
year = list(data.keys())
result = list(data.values())
j=['r','g','b','m','c']
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(year, result, color = j,
width = 0.4)
plt.xlabel("Year")
plt.ylabel("Average Result")
plt.title("Average Result vs. Year")
plt.show()
'''
Output

‘’’

37
Practical 25
‘’’
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 25: WAP to plot a graph for the function y = x2
‘’’

import matplotlib.pyplot as plt


x_cords = range(-50,50)
y_cords = [x*x for x in x_cords]
plt.plot(x_cords, y_cords)
plt.title("Graph of y = x^2")
plt.show()

'''
Output

‘’’

38
Practical 26
'''
Name: Shriya Manuja
Section: A
Batch:2023-25
Practical 26: WAP plot a pie chart on consumption of water in daily life.
'''
import matplotlib.pyplot as plt
water = {'Drinking' : 0.25, 'Washing Clothes/Utensils' : 0.40,
'Bathing' : 0.35}
use = list(water.keys())
val = list(water.values())
plt.pie(val, labels = use, autopct='%1.2f%%')
plt.title("Consumption of Water in Daily Life")
plt.show()
‘’’

Output

‘’’

39
Practical 27

Name: Shriya Manuja


Section: A
Batch:2023-25

Practical 27: WAP to find whether a year is leap year or not

Title- WAP to find whether a year is leap year or not

Code of the program-

year = int(input("Please enter the year: "))


if year%4 ==0:
if year%400 ==0:
print("This year is not a leap year.")
else:
print("This year is a leap year.")
else:
print("This year is not a leap year.")

Output of the program-

Please enter the year: 2013


This year is not a leap year.

40
Practical-28

Name: Shriya Manuja


Section: A
Batch:2023-25

Practical 28: WAP to compute BMI

Title-WAP to compute BMI and if the person's BMI is less than


#18.5 then overweight
#18-25 normal
#25-30 slightly overweight
#30-35 obese
#>35

Code of the program-

height = float(input("Please enter your height in m: "))


weight = float(input("Please enter your weight in kg: "))
BMI = weight/(height**2)
if(BMI<=18.5):
print("Underweight")
elif(BMI>18.5 and BMI<=25):
print("Normal")
elif(BMI>25 and BMI <= 30):
print("Slightly Overweight")
elif(BMI>30 and BMI<= 35):
print("Obese")
elif (BMI>35):
print("Critically Obese")

Please enter your height in m: 1.75


Please enter your weight in kg: 59
Normal

41
Practical 29

Name: Shriya Manuja


Section: A
Batch:2023-25

Title- WAP to imitate treasure hunt game

Code of the Program-

name= input("Please enter your name: ")


print("Welcome " + name + " to the game of Seek the treasure")
print("The game is fun and you might win if you hang in till the end.")
consent= input("Are you ready? Write Yes/No: ")
if consent == "Yes":
print("Good choice!")
print("You are standing on a crossroad, one will take you to the treasure,
the other will lead you to The End.")
L1= input("Which one do you choose? Left/Right:")
if L1 == "Left":
print("Hi! I see you have chosen Left. You are now standing in front of
a cottage. \n What do you choose?")
L2 = input("Choose \n 1 to Open the door, \n 2 to Go to the shed and \n
3 to Go to the Farm")
if L2 == "1":
print("You opened the cottage door now and you have 2 options for
the next step.")
L3 = input("Choose \n 1 to Go to the first floor, \n 2 to go to the
attic")
if L3 =="1":
print("There is fire on the first floor. The End.")
elif L3 == "2":
print("You are in the attic now. There is a chest in front of
you.")
L4= input("Would you like to open the chest? Yes/No:")
if L4 == "Yes":
print("Sorry, you opened a chest full of spiders that ate
you. The End.")
else:
print("You are now stuck in the attic. The End")
else:
print("Wrong choice! The End.")
elif L2 == "2":
print("You are in the shed now. You see a red and a green box.")
L5 = input("Choose \n 1 to open the red box, \n 2 to open the green
box.")
if L5 == "1":
print("You have unlocked the treasure! You win gold and
diamonds")
elif L5 == "2":
print("Oh no! You chose the wrong box. \n This has a bomb. The
End.")
else:
print("Wrong choice! The End.")
elif L2 == "3":
print("The farm had a lion. The End.")
else:
print("Wrong choice! The End.")

42
elif L1== "Right":
print("This was the Wrong choice. There is a crocodile. The End.")
else: print("Alas! Maybe next time?")

Output of the program-

Please enter your name: Oreo


Welcome Oreo to the game of Seek the treasure
The game is fun and you might win if you hang in till the end.
Are you ready? Write Yes/No: Yes
Good choice!
You are standing on a crossroad, one will take you to the treasure, the other
will lead you to The End.
Which one do you choose? Left/Right:Left
Hi! I see you have chosen Left. You are now standing in front of a cottage.
What do you choose?
Choose
1 to Open the door,
2 to Go to the shed and
3 to Go to the Farm2
You are in the shed now. You see a red and a green box.
Choose
1 to open the red box,
2 to open the green box.2
Oh no! You chose the wrong box.
This has a bomb. The End.

43
Practical 30

Name: Shriya Manuja


Section: A
Batch:2023-25

Title- WAP to generate bill from pizza shop depending on user preference from
small,medium, large. Extra topping charge is
separate and extra charge for cheese burst addition.

Code of the program-

tot = 0
name= input("May I know your name?")
print("Welcome to Pizzaza " + name + " What would you like to have?")
size = input("Please choose a size Small/Medium/Large: ")
if size == "Small":
tot=tot+100
x_topping = input("Would you like extra topping Yes/No: ")
if x_topping == "Yes":
tot=tot+30
x_cheese = input("Would you like extra cheese Yes/No: ")
if x_cheese == "Yes":
tot=tot+20
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))
elif x_topping == "No":
x_cheese = input("Would you like extra cheese Yes/No: ")
if x_cheese == "Yes":
tot=tot+20
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))
elif size == "Medium":
tot = tot+200
x_topping = input("Would you like extra topping Yes/No: ")
if x_topping == "Yes":
tot=tot+30
x_cheese = input("Would you like extra cheese Yes/No: ")
if x_cheese == "Yes":
tot=tot+20
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))
elif x_topping == "No":
x_cheese = input("Would you like extra cheese Yes/No: ")
if x_cheese == "Yes":
tot=tot+20
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))
elif size == "Large":
tot = tot+500
x_topping = input("Would you like extra topping Yes/No: ")
if x_topping == "Yes":
tot=tot+50
x_cheese = input("Would you like extra cheese Yes/No: ")

44
if x_cheese == "Yes":
tot=tot+40
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))
elif x_topping == "No":
x_cheese = input("Would you like extra cheese Yes/No: ")
if x_cheese == "Yes":
tot=tot+20
print("Your bill is: "+ str(tot))
elif x_cheese == "No":
print("Your bill is:" + str(tot))

Output of the program-

May I know your name?Shriya


Welcome to Pizzaza Shriya What would you like to have?
Please choose a size Small/Medium/Large: Medium
Would you like extra topping Yes/No: Yes
Would you like extra cheese Yes/No: No
Your bill is:230

45
Practical 31

Name: Shriya Manuja


Section: A
Batch:2023-25

Practical 31- Wap to play stone, paper, scissors with computer

import random
list=["stone","paper","scissor"]
uc=input("Enter user choice: ")
y=random.choice(list)
print("Computer chose",y)
if uc=="stone":
if y=="stone":
print("Tie")
elif y=="paper":
print("Computer wins")
else:
print("User wins")
elif uc=="paper":
if y=="paper":
print("Tie")
elif y=="scissor":
print("Computer wins")
else:
print("User wins")
else:
if y=="scissor":
print("Tie")
elif y=="stone":
print("Computer wins")
else:
print("User wins")

Output:
1.)
Enter user choice: stone
Computer chose paper
Computer wins

2.)
Enter user choice: scissor
Computer chose stone
Computer wins

3.)
Enter user choice: paper
Computer chose stone
User wins

46
Practical 32

Name: Shriya Manuja


Section: A
Batch:2023-25

#WAP that inputs the no. of characters for your password,then it asks for the no
of letters,no of numeric figures, no of special characters to be included. Then
the computer will generate a random password(system generated) for the inputs
taken shuffled

# Shuffled #

import string
import random
alpha=int(input("Enter the number of alphabets required for password: "))
num=int(input("Enter the number of numerics required for password: "))
symbol=int(input("Enter the number of special characters required for password:
"))
a=list(string.ascii_uppercase)+list(string.ascii_lowercase)
n=['0','1','2','3','4','5','6','7','8','9']
s=['!','@','#','$','%','&','*','^']
password=""
pass2=''
y=''
for i in range(0,alpha):
password=password+random.choice(a)
for i in range(0,num):
password=password+random.choice(n)
for i in range(0,symbol):
password=password+random.choice(s)
for i in range(0,alpha+num+symbol):
y=y+password[i]
for i in range(0,alpha+num+symbol):
pass2=pass2+random.choice(y)
print("Shuffled password is ",pass2)

Output:
Enter the number of alphabets required for password: 7
Enter the number of numerics required for password: 7
Enter the number of special characters required for password: 4
Shuffled password is *12#10&8g%98Z1&085

47
#########Not shuffled#######

#WAP that inputs the no. of characters for your password,then it asks for the no
of letters,no of numeric figures, no of special characters to be included. Then
the computer will generate a random password(system generated) for the inputs
taken

import string
import random
alpha=int(input("Enter the number of alphabets required for password: "))
num=int(input("Enter the number of numerics required for password: "))
symbol=int(input("Enter the number of special characters required for password:
"))
a=list(string.ascii_uppercase)+list(string.ascii_lowercase)
n=['0','1','2','3','4','5','6','7','8','9']
s=['!','@','#','$','%','&','*','^']
password=""
for i in range(0,alpha):
password=password+random.choice(a)
for i in range(0,num):
password=password+random.choice(n)
for i in range(0,symbol):
password=password+random.choice(s)
print("Your password is",password)

Output:
Enter the number of alphabets required for password: 7
Enter the number of numerics required for password: 7
Enter the number of special characters required for password: 4
Your password is ysPYZa8697451!$^

48

You might also like