Cs Practical File (Final)

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 48

PROGRAM 1:

Write a program to find whether a given number is perfect or not.

AIM:

To write a python program to check whether the given number is perfect or not.

SOLUTION:

n=int(input("Enter any number: "))


sum=0
for i in range(1,n):
if n%i==0:
sum=sum+i
if sum==n:
print("Perfect number! ")
else:
print("Not a perfect number")

OUTPUT:
PROGRAM 2:

Write a program to check if the entered number is an Armstrong number or not.

AIM :

To write a python program to check whether the given number if Armstrong or


not.

SOLUTION:

# An Armstrong number has sum of the cubes of the digits is equal to the number itself
no=int(input("Enter any number to check: "))
no1=no
sum=0
while(no>0):
ans=no%10
sum=sum+(ans*ans*ans)
no=int(no/10)
if sum==no1:
print("Armstrong number!")
else:
print("Not an Armstrong number")

OUTPUT:
PROGRAM 3:

Write a program to find factorial of the entered number.


AIM :

To write a python program to find the factorial of the given number.

SOLUTION:

num=int(input("Enter the number for calculating its factorial: "))


fact=1
i=1
while i<=num:
fact=fact*i
i=i+1
print("The factorial of",num,"=",fact)

OUTPUT:
PROGRAM 4:

Write a program to enter the number of terms and to print the Fibonacci Series.

AIM :

To write a python program to print the Fibonacci series for the given number of
terms.

SOLUTION:

i=int(input("Enter the limit: "))


x=0
y=1
z=1
print("Fibonacci Series \n")
print(x,y,end=" ")
while(z<=i):
print(z,end=" ")
x=y
y=z
z=x+y

OUTPUT:
PROGRAM 5:

Write a program to enter the string and to check if it is a palindrome or not using
loop.
AIM:

To write a python program to check whether the given string is palindrome or


not.

SOLUTION:

def isPanlindrome(s):
return s==s[::-1]
s=str(input("Enter the string data: "))
ans=isPanlindrome(s)
if ans:
print("Given string is a Palindrome")
else:
print("Given string is NOT a Palindrome")

OUTPUT:
PROGRAM 6:

Write a program to enter the number and print the Floyd's Triangle in
decreasing order.

AIM:

To print the Floyd’s Triangle from the given number to 1 in decreasing order.

SOLUTION:

n=int(input("Enter the number: "))


for i in range(n,0,-1):
for j in range(n,i-1,-1):
print(j,end=" ")
print("\n")

OUTPUT:
PROGRAM 7:

Write a program to enter the numbers and perform linear search and binary
search using list.

AIM:

To python program to perform Linear search and Binary search in a given list.

SOLUTION:

arr=[]
def array_operation():
ch=1
while ch!=5:
print("Various array operations \n")
print("1 Create and enter value \n")
print("2 Print array \n")
print("3 Linear Search \n")
print("4 Binary Search \n")
print("5 Exit \n")

ch=int(input("Enter Choice: "))

if ch==1:
appendarray()
if ch==2:
print_array()
if ch==3:
linear_search()
if ch==4:
binary_search()

def appendarray():
for i in range(0,10):
x=int(input("Enter Number: "))
arr.insert(i,x)

def print_array():
for i in range(0,10):
print(arr[i])

def linear_search():
x=int(input("Enter the number you want to search: "))
fl=0
for i in range(0,10):
if arr[i]==x:
fl=1
print("Number found at %d location"%(i+1))
break
else:
fl==0
print("Number not found")

def binary_search():
x=int(input("Enter the number you want to search: "))
fl=0
low=0
high=len(arr)
while low<=high:
mid=int((low+high)/2)
if arr[mid]==x:
fl=1
print("Number found at %d location"%(mid+1))
break
elif arr[mid]>x:
high=mid-1
else:
low=mid+1
if fl==0:
print("Number not found")

array_operation()

OUTPUT:
PROGRAM 8:

Write a program to sort a list using bubble sort.

AIM:

To write a python program to perform bubble sort in a given list.

SOLUTION:

aList=eval(input("Enter a list: "))


n=len(aList)
for i in range(n):
for j in range(0,n-i-1):
if aList[j]>aList[j+1]:
aList[j],aList[j+1]=aList[j+1],aList[j]
print('List after sorting: ', aList)

OUTPUT:

PROGRAM 9:

Write a program to sort a list using insertion sort.

AIM:

To write a python program to perform insertion sort in a given list

SOLUTION:

aList=eval(input("Enter a list: "))


for i in range(1,len(aList)):
key=aList[i]
j=i-1
while j>=0 and key<aList[j]:
aList[j+1]=aList[j]
j=j-1
else:
aList[j+1]=key
print("List after sorting: ",aList)

OUTPUT:

PROGRAM 10:

Write a program to sort a list using selection sort.

AIM:

To write a python program to perform selection sort in a given list.

SOLUTION:

A=eval(input("Enter a list: "))


for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print("List after sorting: ",A)

OUTPUT:

PROGRAM 11:

Write a program to implement stack operations.

AIM:

To write a python program to implement the stack operations

SOLUTION:

def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[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 from (1-5):"))
if ch==1:
item=int(input("enter item:"))
Push(Stack,item)
elif ch==2:
item=Pop(Stack)
if item=="underflow":
print("Underflow!!, stack is empty")
else:
print("Popped item is:",item)
elif ch==3:
item=Peek(Stack)
if item=="underflow":
print("Underflow!!, stack is empty")
else:
print("Topmost item is:",item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice")def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[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 from (1-5):"))
if ch==1:
item=int(input("enter item:"))
Push(Stack,item)
elif ch==2:
item=Pop(Stack)
if item=="underflow":
print("Underflow!!, stack is empty")
else:
print("Popped item is:",item)
elif ch==3:
item=Peek(Stack)
if item=="underflow":
print("Underflow!!, stack is empty")
else:
print("Topmost item is:",item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice")

OUTPUT:
PROGRAM 12:

Write a program to implement queue operations.

AIM:

To write a python program to implement the queue operations.

SOLUTION:

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):
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[0],"<-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")
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:"))
if ch==1:
item=int(input("Enter the 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:
PROGRAM 13:

Write a program to read the data and count the number of occurrences of a given
string in the file.

AIM:

To write a python program to count the number of occurrences of a given string


in a file.

TEXT FILE: TEST.TXT

SOLUTION:

f=open("test.txt",'r')
r=f.readlines()
f.close()
chk=input("Enter String to search : ")
count=0
for word in r:
line=word.split()
for cr in line:
line2=cr
if chk==line2:
count+=1
print("The search String ", chk, "is present : ", count, "times")

OUTPUT:
PROGRAM 14:

Write a program to read data from data file in read mode and append the words
starting with letter ‘T’ in a given file in python.

AIM:

Write a python program to read the data and append the words starting with “T”
in a given file .

TEXT FILE: TEST.TXT

SOLUTION:

f=open("test.txt",'r')
read=f.readlines()
f.close()
id=[]
for ln in read:
if ln.startswith("T"):
id.append(ln)
print(id)

OUTPUT:
PROGRAM 15:
Write a program to read data from data file and show Data File Handling related
functions utility in python.

AIM:

Write a python program to perform file handling functions.

TEXT FILE: TEST.TXT

SOLUTION:

f=open("C:/Users/Z3-Z22/Documents/test.txt",'r')
print(f.name)
f_contents=f.read()
print(f_contents)
print()
f.seek(0)
f_contents=f.readlines()
print(f_contents)
print()
f.seek(0)
f_contents=f.readline()
print(f_contents)
print()
f.seek(0)
for line in f:
print(line)
f.seek(0)
print()
f_contents=f.read(50)
print(f_contents)
print()
size_to_read=10
f_contents=f.read(size_to_read)
while len(f_contents)>0:
print(f_contents)
print(f.tell())
f_contents=f.read(size_to_read)

OUTPUT:
PROGRAM 16:

Write a program to display unique vowels present in the given word using Stack.

AIM:

To write a python program to display the unique vowels present in the given
string .

SOLUTION:

vowels =['a','e','i','o','u']
word = input("Enter the word to search for vowels :")
Stack = []
for letter in word:
if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print("The number of different vowels present in",word,"is",len(Stack))

OUTPUT:
PROGRAM 17:

Write a python program to write the data in a CSV file student.csv and also to
read and display the data from the file.

AIM:

To write a python program to write the data in a csv file and also read and
display the data from a csv file.

SOLUTION:

#writing data
import csv
fh=open("d:\student.csv","w")
stuwriter=csv.writer(fh)
stuwriter.writerow([1,'aman',50])
stuwriter.writerow([2,'Raman',60])
fh.close()
#reading and displaying data
fh=open("d:\student.csv","r")
stureader=csv.reader(fh)
for rec in stureader:
print(rec)
fh.close()

OUTPUT:
PROGRAM 18:

Write a python program to perform basic operations in a binary file using pickle
module.

AIM:

To write a python program to perform the basic operations in a binary file using
pickle module.

SOLUTION:

# Program to write and read employee records in a binary file


import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()

OUTPUT:
PROGRAM 19:

(i) Display the Mobile company. Mobile name & price in descending order of
their manufacturing date.

(ii)  List the details of mobile whose name starts with “S”.

(iii)  Display the Mobile supplier & quantity of all mobiles except  “MB003‟.
(iv)  To display the name of mobile company having price between 3000 &
5000.

**Find Output of following queries


(v)  SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;
(vi)  SELECT MAX(M_Mf_Date), MIN(M_Mf_Date) FROM MobileMaster;
(vii)  SELECT  M1.M_Id, M1.M_Name, M2.M_Qty, M2.M_Supplier
FROM MobileMaster M1, MobileStock M2 WHERE M1.M_Id=M2.M_Id
AND M2.M_Qty>=300;
(viii)  SELECT AVG(M_Price) FROM MobileMaster;
SOLUTION:
PROGRAM 20:

i. Display the Trainer Name, City & Salary in descending order of their
Hiredate.
ii. To display the TNAME and CITY of Trainer who joined the Institute in
the month of December 2001.

iii. To display TNAME, HIREDATE, CNAME, STARTDATE from tables  TRAINER


and COURSE of all those courses whose FEES is less than or  equal to 10000.
iv. To display number of Trainers from each city.

**Find Output of following queries

v. SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT  IN(‘DELHI’,


‘MUMBAI’);

vi. SELECT DISTINCT TID FROM COURSE;


vii. SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY  TID
HAVING COUNT(*)>1;
viii. SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE  STARTDATE<
‘2018-09-15’;
SOLUTION:
PROGRAM 21:

i) To display details of those Faculties whose salary is greater than 12000.


ii) To display the details of courses whose fees is in the range of 15000 to
50000 (both values included).
iii) To increase the fees of all courses by 500 of “System Design” Course.
(iv) To display details of those courses which are taught by ‘Sulekha’ in
descending order of courses.

**Find output of following

v) Select COUNT(DISTINCT F_ID) from COURSES;

vi) Select MIN(Salary) from FACULTY,COURSES where COURSES.F_ID =


FACULTY.F_ID;
vii) Select sum(fees) from COURSES where F_ID = 102;
viii) Select avg(fees) from COURSES;
SOLUTION:
PROGRAM 22:

Write python code to display employee details whose salary is more than 70,000.

AIM:

To display the employee details whose salary is more than 70000.

SOLUTION:

import mysql.connector as sqltor


mycon=sqltor.connect(host="localhost",user="root",password="zee123",database="em
pl")

cursor=mycon.cursor()

cursor.execute("create table emp (Eno integer primary key,Ename varchar(20),salary


int(10))")

total=int(input("enter total number of records"))

for i in range(total):

no=int(input("Enter the employee number "))

name=input("Enter employee name ")

salary=int(input("Enter the Salary "))

cursor.execute("insert into emp values({},'{}',{})".format(no,name,salary))

mycon.commit()

cursor.execute("select * from emp where salary>70000")

data=cursor.fetchall()

for row in data:

print(row)
OUTPUT:

PROGRAM 23:
Write a python code to update the salary by thousand for employees whose
salary is less than 8,000.

AIM:

To write a python program to update the salary by thousand for employees


whose salary is less than 8000.

SOLUTION:

import mysql.connector as sqltor


mycon=sqltor.connect(host="localhost",user="root",password="zee123",database="em
pl")

cursor=mycon.cursor()

cursor.execute("create table emp2 (Eno integer primary key ,Ename varchar(20),salary


int(10))")

total=int(input("enter total number of records"))

for i in range(total):

no=int(input("Enter the employee number "))

name=input("Enter employee name ")

salary=int(input("Enter the Salary "))

cursor.execute("insert into emp2 values({},'{}',{})".format(no,name,salary))

mycon.commit()

cursor.execute("update emp2 set salary=salary+1000 where salary<80000")

mycon.commit()

cursor.execute("select * from emp2")

data=cursor.fetchall()

for row in data:

print(row)
OUTPUT:

PROGRAM 24:
Write a python code to delete the record with the given salary.

AIM:

To write a python program to delete the record with the given salary.

SOLUTION:

import mysql.connector as sqltor


mycon=sqltor.connect(host="localhost",user="root",password="zee123",database="em
pl")

cursor=mycon.cursor()

cursor.execute("create table emp3 (Eno integer primary key ,Ename varchar(20),salary


int(10))")

total=int(input("enter total number of records"))

for i in range(total):

no=int(input("Enter the employee number "))

name=input("Enter employee name ")

salary=int(input("Enter the Salary "))

cursor.execute("insert into emp3 values({},'{}',{})".format(no,name,salary))

mycon.commit()

delsal=int(input("Record to be Deleted with the Salary ?:"))

cursor.execute("DELETE from emp3 where salary={}".format(delsal))

mycon.commit()

cursor.execute("select * from emp3")

data=cursor.fetchall()

for row in data:

print(row)
OUTPUT:

PROGRAM 25:

Write a python code to display all the records in a database one by one.
AIM:

To write a python code to display all the records in a database one by one.

SOLUTION:

import mysql.connector as sqltor


mycon=sqltor.connect(host="localhost",user="root",password="zee123",database="em
pl")

cursor.execute("create table emp4 (Eno integer primary key ,Ename varchar(20),salary


int(10))")

total=int(input("enter total number of records"))

for i in range(total):

no=int(input("Enter the employee number "))

name=input("Enter employee name ")

salary=int(input("Enter the Salary "))

cursor.execute("insert into emp4 values({},'{}',{})".format(no,name,salary))

mycon.commit()

cursor.execute("select * from emp4")

while True:

data=cursor.fetchone()

if data==None:

break

else:

print("\nNext record")

print(data)
OUTPUT:

You might also like