0% found this document useful (0 votes)
68 views52 pages

Practical File

The document contains instructions for 30 practical programming assignments covering topics like dictionaries, conditional statements, functions, sorting algorithms, file handling, recursion, and data structures. Some of the key tasks mentioned include creating a dictionary of competition winners, a menu-driven calculator program, functions for arithmetic operations and calculating areas, and programs involving sorting, searching, and binary search algorithms.

Uploaded by

Amandeep Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views52 pages

Practical File

The document contains instructions for 30 practical programming assignments covering topics like dictionaries, conditional statements, functions, sorting algorithms, file handling, recursion, and data structures. Some of the key tasks mentioned include creating a dictionary of competition winners, a menu-driven calculator program, functions for arithmetic operations and calculating areas, and programs involving sorting, searching, and binary search algorithms.

Uploaded by

Amandeep Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Practical File

PRACTICAL FILE
C.SC. (2019-20)
1 Create a dictionary containing names of competition
winner students as keys and number of their wins as
values.
2 Write a program to input any choice and to implement the
following
Choice Find
1                                          Area of Circle
2                                          Area of Rectangle
3                                          Area of Triangle
3 Write a program that reads a line and prints its statistics
like:
Number of uppercase letters:
Number of uppercase letters:
Number of digits:
4 Write a program to sort a list using Bubble Sort.
5 Write a program to sort a list using Insertion Sort.
6 Write a Python program to test if a string is a palindrome
or not.
7 Write a program that receives two numbers in a function
and returns the results of all Arithmetic operations on
these numbers
8 NOT IN SLLYABUS
9 Write a function to swap the values of two variables
through a function.
10 Write a program that has a function which takes two
numbers and returns the number that has minimum one’s
digit.
11 Create a module area.py that stores functions to calculate
area of circle, a square & rectangle and use the module in
calc.py
12 Create a library geometry and import this into a file
implib.py file.
13 Write a random number generator using functions that
generates random numbers between 1 and 6 (simulates a
dice).
14 Open a webpage using the url library.
15 Read a file line by line and print it.

16 To display the number of lines in the file and size of a file


in bytes.
17 Remove all the lines that contain the character `a' in a file
and write it to another file.
18 To get roll numbers , names and marks of the students of
a class(get from users ) and store these details in a file
called "Marks.dat".
19 Recursively find the factorial of a natural number.

20 Write a recursive code to find the sum of all elements of a


list .

21 Write a recursive function to print a string backwards.


22 Write a recursive code to compute the nth Fibonacci
number.
23 Write a recursive code to search an element in an array (a
sorted list) using Binary Search .
24 Write a recursive Python program to test if a string is a
palindrome or not.
25 Write a program to search an element in an array (a sorted
list) using Binary Search .
26 Write a program for linear search.
27 Write a program for insertion.(2 methods)
28 Write a program for deletion.
29 Write a program for bubble sort.
30 Write a menu based program to perform the operation on
stack in python.
31 Write a menu based program to perform the operation on
queue in python.
32 Write a menu based program for circular queue.

33 Create a graphical application that accepts user inputs,


performs some operation on them, and then writes the
output on the screen. e.g. a small calculator. (use tkinter
library)
34 Write a Python program to plot the function y = x2 using the
pyplot or matplotlib libraries.
35 Compute EMIs for a loan using the numpy or scipy
libraries.
36 Write a Python function sin(x, n) to calculate the value of
sin(x) using its Taylor series expansion up to n terms.
Compare the values of sin(x) for different values of n with
the correct value.
SQL Queries : (Total – 50)
Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL,
3 ORDER BY, GROUP BY HAVING
7
3 Queries for Aggregate functions- SUM( ), AVG( ), MIN( ),
8 MAX( ), COUNT( )
PRACTICAL -1

Create a dictionary containing names of competition winner students as keys and


number of their wins as values.
CODE:
n=int(input("How many students?: "))
CompWinners={}
for a in range(n):
key=input("Name of student: ")
value=int(input("Number of competitions won:" ))
CompWinners[key]=value
print("The dictionary now is : ")
print(CompWinners)
OUTPUT:
How many students?: 2
Name of student: Nita
Number of competitions won:3
Name of student: Rosy
Number of competitions won:1
The dictionary now is :
{'Nita': 3, 'Rosy': 1}

PRACTICAL -2

Q-Write a program to input any choice and to implement the following:


Choice……………..Find
1 Area of circle
2 Area of rectangle
3 Area of triangle
Code:
print("Choose one of the options given below")
print("""1- Area of circle
2- Area of rectangle
3- Area of triangle""")
l=area=b=ba=h=s=0
choice=int(input("Enter one of the choice: "))
if choice==1:
r=float(input("Enter side of square: "))
area=r*r*3.14
print("Area of circle: ",area)
elif choice==2:
l=float(input("Enter length of rectangle: "))
b=float(input("Enter breadth of rectangle: "))
area=l*b
print("Area of rectangle:",area)
elif choice==3:
h=float(input("Enter height of triangle : "))
ba=float(input("Enter base of triangle : "))
area=0.5*h*ba
print("Area of triangle: ",area)
print("---Program ended---")

Output:
Choose one of the options given below
1- Area of square
2- Area of rectangle
3- Area of triangle
Enter one of the choice: 1
Enter side of square: 5
Area of square: 25.0
PRACTICAL 3

Write a program that reads a line and prints its statistics like:
Number of uppercase letters:
Number of uppercase letters:
Number of digits:
CODE:
line=input("Enter a line : ")
lowercount=uppercount=digitcount=0
for a in line:
if a.islower():
lowercount+=1
elifa.isupper():
uppercount+=1
elifa.isdigit():
digitcount+=1
print("Number of lowercase characters : ",lowercount)
print("Number of uppercase characters : ",uppercount)
print("Number of digits : ",digitcount)
OUTPUT:
Enter a line : A1z B2y hsq10aMD
Number of lowercase characters : 6
Number of uppercase characters : 4
Number of digits : 4
PRACTICAL 4
Write a program to sort a list using Bubble sort
CODE:
l=eval(input("Enter list: "))
print("Original List: ",l)
n=len(l)
for i in range(n):
for j in range(0,n-i-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print("List after sorting : ",l)
OUTPUT:
Enter list: [15,6,13,22,3,52,1]
Original List: [15, 6, 13, 22, 3, 52, 1]
List after sorting : [1, 3, 6, 13, 15, 22, 52]
PRACTICAL 5
Write a program to sort a list using insertion sort
CODE:
l=eval(input("Enter list: "))
print("Original List: ",l)
n=len(l)
for i in range(1,n):
key=l[i]
j=i-1
while j>=0 and key < l[j]:
l[j+1]=l[j]
j-=1
else:
l[j+1]=key
print("List after sorting :",l)
OUTPUT:
Enter list: [15,6,13,22,3,52,1]
Original List: [15, 6, 13, 22, 3, 52, 1]
List after sorting : [1, 3, 6, 13, 15, 22, 52]

PRACTICAL 6
Write a program that reads a string and checks whether it is a palindrome string
or not
CODE
string=input("Enter a string:" )
length=len(string)
mid=int(length/2)
rev=-1
for a in range(mid):
if string[a]==string[rev]:
a+=1
rev-=1
else:
print(string,'is not a palindrome')
break
else:
print(string,"is a palindrome")
OUTPUT
Enter a string: madam
madam is a palindrome

PRACTICAL 7
Write a program that receives two numbers in a function and returns the results
of all Arithmetic operations on these numbers.
CODE:
deftcalc(x,y):
returnx+y,x-y,x*y,x/y,x%y
num1=int(input("Enter number 1 : ")) #integer
num2=int(input("Enter number 2 : ")) #integer
add,sub,mult,div,mod=tcalc(num1,num2)
print("Sum of given numbers : ",add)
print("Subtraction of given numbers : ",sub)
print("Product of given numbers : ",mult)
print("Division of given numbers : ",div)
print("Modulo of given numbers : ",mod)
OUTPUT:
Enter number 1 : 5
Enter number 2 : 10
Sum of given numbers : 15
Subtraction of given numbers : -5
Product of given numbers : 50
Division of given numbers : 0.5
Modulo of given numbers : 5

PRACTICAL 9
Write a function to swap the values of two variables through a function.
CODE:
defexno(x,y):
x,y=y,x
returnx,y
a=int(input("Variable 1 : "))
b=int(input("Variable 2 : "))
a,b=exno(a,b)
print("After Exchanging-")
print("Value of variable 1 : ",a)
print("Value of variable 2 : ",b)
OUTPUT:
Variable 1 : 2
Variable 2 : 9
After Exchanging-
Value of variable 1 : 9
Value of variable 2 : 2

PRACTICAL 10
Write a program that has a function which takes two numbers and returns the
number that has minimum one’s digit.
CODE:
defmincheck(p,q):
sp=str(p)
sq=str(q)
d1=sp[-1]
d2=sq[-1]
ifint(d1)>int(d2):
return q
else:
return p
a=int(input("Enter a number : "))
b=int(input("Enter another number : "))
print("Number having minimum one's digit is : ",mincheck(a,b))
OUTPUT:
Enter a number : 1235680
Enter another number : 1239
Number having minimum one's digit is : 1235680

PRACTICAL 11
Create a module area.py that stores functions to calculate area of circle, a square
& rectangle and use the module in calc.py.
CODE 1: #-------------------area.py-----------------
defarcircle(r):
return 3.14*r*r
defarsquare(s):
return s*s
defarrectangle(l,b):
return l*b
CODE 2: #-----------------calc.py--------------
import area
print('Enter choice for area : ')
print('''1. Circle
2. Square
3. Rectangle''')
n=int(input("Enter choice: "))
if n==1:
rs=float(input("Enter radius : "))
print("Area of circle : ",area.arcircle(rs))
elif n==2:
se=float(input("Enter side : "))
print("Area of square : ",area.arsquare(se))
elif n==3:
lh=float(input("Enter length : "))
bh=float(input("Enter breadth : "))
print("Area of rectangle : ",area.arrectangle(lh,bh))

OUTPUT:
Enter choice for area :
1. Circle
2. Square
3. Rectangle
Enter choice: 2
Enter side : 5
Area of square : 25.0
PRACTICAL 12
Create a library geometry and import this into a file implib.py file.
CODE:
GEOMETRY LIBRARY CONTAIN TWO MODULE NAMED – circlestat and squarestat
MODULE circlestat :-
defar_circle(r):
a=3.14*r*r
return a
defpr_circle(r):
p=2*3.14*r
return p
MODULE squarestat :-
defar_square(s):
ar=s*s
return ar
defpr_square(s):
p=4*s
return p
MAIN PROGRAM –
Implib from geometry import circlestat,squarestat
print("""Which shape statistics do you want to find:
1. Square
2. Circle""")
c=int(input("Enter choice : "))
if c==1:
side=float(input("Enter side : "))
choice=int(input("Enter what do you want to find 1-Area,2-Perimeter : "))
if choice==1:
area=squarestat.ar_square(side)
print("Area of square : ",area)
elif choice==2:
perimeter=squarestat.pr_square(side)
print("Perimeter of square : ",perimeter)
elif c==2:
ra=float(input("Enter radius : "))
choice=int(input("Enter what do you want to find 1-Area,2-Perimeter : "))
if choice==1:
area=circlestat.ar_circle(ra)
print("Area of circle : ",area)
elif choice==2:
perimeter=circlestat.pr_circle(ra)
print("Perimeter of circle : ",perimeter)
OUTPUT:
Which shape statistics do you want to find:
1. Square
2. Circle
Enter choice : 1
Enter side : 1
Enter what do you want to find 1-Area,2-Perimeter : 1
Area of square : 1.0

PRACTICAL 13
Write a random number generator using functions that generates random
numbers between 1 and 6 (simulates a dice).
CODE:
import random
def dice():
rn=random.randint(1,6)
return rn
print("The dice face is showing number : ")
print(dice())
OUTPUT 1:
The dice face is showing number :
5
OUTPUT 2:
The dice face is showing number :
1
PRACTICAL 14
Open a webpage using the urllib library.
CODE:
Import urllib
import urllib.request
import webbrowser
weburl=urllib.request.urlopen('http://www.google.com/')
html=weburl.read()
data=weburl.getcode()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info()
print("The url is : ",url)
print("The HTTP code status is : ",data)
print("headers returned \n",hd)
print("the info() returned :\n",inf)
print("Now opening the url",url)
webbrowser.open_new(url)
OUTPUT:
The urlis : http://www.google.com/
The HTTP code status is : 200
headers returned
Date: Tue, 23 Jul 2019 06:26:31 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: 1P_JAR=2019-07-23-06; expires=Thu, 22-Aug-2019 06:26:31 GMT;
path=/; domain=.google.com
Set-Cookie:
NID=188=wJDX1COyIxeiakmLKkHgHoFVSefxteV9FtiFlJSTFOERNhkb_1R0GQeN9u_
2ud5G3wWhAj43EE3JcRscqcXSAEdk4NbKFe5Neswni5bQYAfWyx3D0hLU1RwG821
oP36jLJCAMu4GWGNiD7GokX5_h5XwJRbBaXgUW-AhMlibSM0; expires=Wed, 22-
Jan-2020 06:26:31 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding
Connection: close

the info() returned :


Date: Tue, 23 Jul 2019 06:26:31 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: 1P_JAR=2019-07-23-06; expires=Thu, 22-Aug-2019 06:26:31 GMT;
path=/; domain=.google.com
Set-Cookie:
NID=188=wJDX1COyIxeiakmLKkHgHoFVSefxteV9FtiFlJSTFOERNhkb_1R0GQeN9u_
2ud5G3wWhAj43EE3JcRscqcXSAEdk4NbKFe5Neswni5bQYAfWyx3D0hLU1RwG821
oP36jLJCAMu4GWGNiD7GokX5_h5XwJRbBaXgUW-AhMlibSM0; expires=Wed, 22-
Jan-2020 06:26:31 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding
Connection: close

Now opening the url http://www.google.com/


PRACTICAL 15
Reading a complete file – line by line
CODE
myfile=open(r'D:\Ritik\poem.txt','r')
str=" "
whilestr:
str=myfile.readline()
print(str,end= ' ')
myfile.close()

OUTPUT
why?
we work, we try to be better
we work with full zest
But, why is that we just we don't know any letter .

we still give our best,


we have to steal,
But,why is that we still don't get a meal.

we don't get luxury ,


we don't get childhood ,
But we still work,
Not for us, but for others.

why is it that some kids wear shoes, BUT we make them ?

PRACTICAL 16
To display the number of lines in the file and size of a file in bytes.

CODE:
f=open(r'D:\Ritik\poem.txt','r')
nl=s=0
for line in f:
nl+=1
s+=len(line)
f.close()
print("Number of Lines: ",nl)
print("Size of file (in bytes) : ",s)

OUTPUT:
Number of Lines: 15
Size of file (in bytes) : 356
PRACTICAL 17
Remove all the lines that contain the character `a' in a file and write it to another
file.

CODE:
inpf=open(r'D:\Ritik\poem.txt','r')
outf=open(r'w.txt','w')
for line in inpf:
if 'a' not in line:
outf.write(line)
print(“File written successfully with lines which does not contain letter ‘a’. ”)
inpf.close()
outf.close()

OUTPUT:
File written successfully with lines which does not contain letter ‘a’.
PRACTICAL 18
Write a program to get roll numbers, names and marks of the student of a class
(get from user) and store these details in a file called “Marks.det”
CODE
file=open(r'C:\Users\Student\Documents\myfile1.txt',"w")
count=int(input("How many students are there in class? "))
rec=''
for i in range(count):
print("Enter details for student",(i+1),'below:')
rollno=int(input("Rollno: "))
name=input("Name: ")
marks=float(input("Marks: "))
rec=str(rollno)+','+name+','+str(marks)+'\n'
file.write(rec)
file.close()

OUTPUT
How many students are there in class? 2
Enter details for student 1 below:
Rollno: 10
Name: Jatin
Marks: 86
Enter details for student 2 below:
Rollno: 15
Name: Jiya
Marks: 78.9
PRACTICAL 19
Recursively find the factorial of a natural number.
CODE:
def fact(n):
if n<2:
return 1
else:
return n*fact(n-1)
num=int(input("Enter number : "))
res=fact(num)
print("Factorial of",num," : ",res)
OUTPUT:
Enter number : 5
Factorial of 5 : 120
PRACTICAL 20
Write a recursive code to find the sum of all elements of a list.
CODE:
def suml(ar):
if len(ar)==0:
return ar[0]
else:
return ar[0]+sum(ar[1:])
a=eval(input("Enter array : "))
N=len(a)
res=suml(a)
print("Sum : ",res)

OUTPUT:
Enter array : [1,9,2,7,3,6]
Sum : 28
PRACTICAL 21
Write a recursive function to print a string backwards.
CODE:
defbg(sg,n):
if n>0:
print(sg[n],end='')
bg(sg,n-1)
elif n==0:
print(sg[0])
s=input("Enter string : ")
bg(s,len(s)-1)

OUTPUT:
Enter string : Hello
olleH
PRACTICAL 22
Write a recursive code to compute the nth Fibonacci number.
CODE:
def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
num=int(input("Enter number : "))
for i in range(1,num+1):
print(fib(i),end=',')
print("...")

OUTPUT:
Enter number : 10
0,1,1,2,3,5,8,13,21,34,...
PRACTICAL 23
Write a recursive code to search an element in an array (a sorted list) using
Binary Search .
CODE:
defBsearch(lst,low,high,val):
if low>high:
return -999
mid = int((low+high)/2)
iflst[mid]==val:
return mid
elifval<lst[mid]:
high=mid-1
returnBsearch(lst,low,high,val)
else:
low=mid+1
returnBsearch(lst,low,high,val)
l=eval(input("Enter list : "))
item=int(input("Enter element to be searched : "))
res=Bsearch(l,0,len(l)-1,item)
if res>=0:
print("Element found at index : ",res)
else:
print("Element not found ")

OUTPUT:
Enter element to be searched : 9
Element found at index : 5

PRACTICAL 24
Write a recursive Python program to test if a string is a palindrome or not.
CODE:
def palindrome(s):
iflen(s)<=1:
return True
else:
if s[0]==s[-1]:
return palindrome(s[1:-1])
else:
return False
a=str(input("enter a string--->"))
if palindrome(a)==True :
print("string is a palindrome")
else:
print("string is not a palindrome")

OUTPUT:
enter a string--->madam
string is a palindrome

PRACTICAL 25
Write a program to search an element in an array (a sorted list) using
Binary Search .
CODE:
defbinsearch(ar,key):
low=0
high=len(ar)-1
while low<=high:
mid=int((low+high)/2)
if key==ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
else:
return -999
l=[1,3,4,6,7,9,10]
i=int(input("Enter value to be found : "))
r=binsearch(l,i)
if r>=0:
print("Element found at index : ",r)
else:
print("Element not found ")
OUTPUT:
Enter value to be found : 6
Element found at index : 3
PRACTICAL 26
Write a program for linear search.
CODE:
defLsearch(ar,item):
i=0
while i <len(ar) and ar[i]!=item:
i+=1
if i<len(ar):
return i
else:
return False
N=int(input("Enter desired linear list size : "))
print("Enter elements for Linear list")
AR=[0]*N
for i in range(N):
AR[i]=int(input("Element "+str(i)+' : '))
ITEM=int(input("Enter element to be searched: "))
index=Lsearch(AR,ITEM)
if index:
print("Element found at index : ",index)
else:
print("Element not found ")

OUTPUT:
Enter desired linear list size : 3
Enter elements for Linear list
Element 0 : 1
Element 1 : 3
Element 2 : 5
Enter element to be searched: 3
Element found at index : 1
PRACTICAL 27
Write a program for insertion.(Menu based ,2 methods)
CODE:
import bisect
defBinsert(ar,item):
ind=bisect.bisect(ar,item)
bisect.insort(ar,item)
returnind
defFindPos(ar,item):
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1
for i in range(size-1):
ifar[i]>item:
pos=i
break
returnpos
def Shift(ar,pos):
ar.append(None)
ifpos!=-1:
size=len(ar)
i=size-1
while i>=pos:
ar[i]=ar[i-1]
i-=1
mylist=[10,20,30,40,50]
print("Sorted List : ",mylist)

while True:
print("Insertion methods: ")
print("1. Traditional")
print("2. Bisect module")
print("3. Exit")
item=int(input("Enter element : "))
ch=int(input("Enter choice: "))
ifch==1:
p=FindPos(mylist,item)
Shift(mylist,p)
mylist[p]=item
print("After inserting by traditional method")
print("Element inserted at position ",p)
print("List after inserting : ")
print(mylist)
print()
elifch==2:
p=Binsert(mylist,item)
print("After inserting by bisect method")
print("Element inserted at position ",p)
print("List after inserting : ")
print(mylist)
elifch==3:
break
else:
print("Enter valid choice")
OUTPUT:
Enter choice: 1
After inserting by traditional method
Element inserted at position 3
List after inserting :
[10, 20, 30, 36, 40, 50]
Insertion methods:
1. Traditional
2. Bisect module
3. Exit
Enter element : 25
Enter choice: 2
After inserting by bisect method
Element inserted at position 2
List after inserting :
[10, 20, 25, 30, 36, 40, 50]
Insertion methods:
1. Traditional
2. Bisect module
3. Exit
Enter element : 1
Enter choice: 3
PRACTICAL 28
Write a program for deletion.
CODE:
defBsearch(ar,key):
low=0
high=len(ar)-1
while low<=high:
mid=int((low+high)/2)
if key==ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
else:
return False

mylist=[10,5,1,23,9]
item=int(input("Enter item: "))
p=Bsearch(mylist,item)
if p:
delmylist[p]
print("List after deletion : ",mylist)
else:
print("No element in list")
OUTPUT:
Enter item: 1
List after deletion : [10, 5, 23, 9]
PRACTICAL 29
Write a program for Bubble Sort.
CODE-:
aList=[15,6,13,22,3,52,2]
print(“Original list is:”,aList)
n=len(aList)
#Traverse through all list elements
for i in range (n):
#Last i elements are already in place
for j in range(0,n-i-1):
#traverse the list from 0 to n-i-1
#Swap if the element found is greater
#than the next element
if aList[j] > aList[j+1]:
if aList[j] , aList[j+1] = aList[j+1] , aList [j]
print (“List after sorting :”,aList)

OUTPUT:-
Original list is: [15, 6, 13, 22, 3, 52, 2]
List after sorting : [2, 3, 6, 13, 15, 22, 52]

PRACTICAL 30
Write a menu based program to perform the operation on stack in python.
CODE:

def Push(stack,item):
stack.append(item)
top=len(stack)-1
def Pop(stack):
if stack==[]:
return "Underflow"
else:
item=stack.pop()
iflen(stack)==0:
top==None
else:
top=len(stack)-1
return item
def Peek(stack):
if stack==[]:
return "Underflow"
else:
top=len(stack)-1
return stack[top]
def Display(stack):
if stack==[]:
print("stack empty")
else:
top=len(stack)-1
print(stack[top],"<--top")
for a in range(top-1,-1,-1):
print(stack[a])
stack=[]
top=None
while True:
print("Stack operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display Stack")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
ifch==1:
item=int(input("Enter item:"))
Push(stack,item)
elifch==2:
item=Pop(stack)
if item=="Underflow":
print("Underflow! stack is empty")
else:
print("Popped item is:",item)
elifch==3:
item=Peek(stack)
if item =="Underflow":
print("Underflow! stack is empty!")
else:
print("Topmost item is",item)
elifch==4:
Display(stack)
elifch==5:
break
else:
print("invalid choice!")

OUTPUT:
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):1
Enter item:20
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):1
Enter item:10
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):2
Popped item is: 10
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):3
Topmost item is 20
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):4
20 <--top
Stack operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):5
Practical -31
Write a menu based program to perform the operation on queue in python.
CODE-:

############## queue IMPLEMENTATION ##############


"""
queue:implemented as a list
front:integer having position of fisrt (frontmost) element in queue
rear:integer having position of last element in queue
"""
def cls():
print("/n"*100)

def isEmpty(Qu):
if Qu==[]:
return True
else:
return False

def Enqueue(Qu,item):
Qu.append(item)
if len(Qu)==1:
front=rear=0
else:
rear=len(Qu)-1

def Dequeue(Qu):
if isEmpty(Qu):
return "Underflow"
else:
item=Qu.pop(0)
if len(Qu)==0:
front=rear=None
return item

def Peek(Qu):
if isEmpty(Qu):
return "Underflow"
else:
front=0
return Qu[front]

def Display(Qu):
if isEmpty(Qu):
print("Queue Empty!")
elif len(Qu)==1:
print(Qu[front],"<-front,rear")
else:
front=0
rear=len(Qu)-1
print(Qu[front],"<-front")
for a in range(1,rear):
print(Qu[a])
print(Qu[rear],"<-rear")

#main_program
queue=[]
front=None
while True :
cls()
print("QUEUE OPERATIONS")
print("1.Enqueue")
print("2.Dequeue")
print("3.Peek")
print("4.Display queue")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Enqueue(queue,item)
input("Press Enter to continue...")
elif ch==2:
item=Dequeue(queue)
if item=="Underflow":
print("Underflow!Queue is empty!")
else:
print("Dequeue-ed item is",item)
input("Press Enter to continue...")
elif ch==3:
item=Peek(queue)
if item=="Underflow":
print("Queue is empty!")
else:
print("Frontmost item is",item)
input("Press Enter to continue...")
elif ch==4:
Display(queue)
input("Press Enter to continue...")
elif ch==5:
break
else:
print("Invalid Choice")
input("Press Enter to continue...")

OUTPUT-:
/
n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n
/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/
n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n
QUEUE OPERATIONS
1.Enqueue
2.Dequeue
3.Peek
4.Display queue
5.Exit
Enter your choice(1-5):3
Frontmost item is 5
Press Enter to continue...

Practical-32
Write a menu based program for circular queue.
CODE-:

You might also like