0% found this document useful (0 votes)
116 views30 pages

Practical Programs: Name - Yakesh Balaji Raja.P

The document describes 12 programming exercises involving lists, files, and data structures in Python. The exercises cover topics like linear and binary search on lists, sorting doctor and product details, analyzing text files, reading and writing to binary and CSV files, and calculating sums of nested list elements. Functions are used to implement sorting, searching, I/O, and calculations in the exercises.

Uploaded by

krithik
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)
116 views30 pages

Practical Programs: Name - Yakesh Balaji Raja.P

The document describes 12 programming exercises involving lists, files, and data structures in Python. The exercises cover topics like linear and binary search on lists, sorting doctor and product details, analyzing text files, reading and writing to binary and CSV files, and calculating sums of nested list elements. Functions are used to implement sorting, searching, I/O, and calculations in the exercises.

Uploaded by

krithik
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/ 30

Name - Yakesh Balaji Raja.

Practical Programs
Ex.no-1

Linear search and Binary search

Aim:

To write an menu driven program to apply linear search and binary search for a list
of string using functions.

Program:

def binary():

r='false'

a.sort()

if val <= (len(a)//2):

for i in range(0, ((len(a)//2)+1)):

if str(a[i]) == str(val):

r='true'

elif val >= (len(a)//2):

for j in range(((len(a)//2)-1),len(a)):

if str(a[j]) == str(val):

r='true'

if r == 'true':

print(val,' is found in the list')

elif r=='false':

print(val,' is not found in the list')


def linear():

r1='false'

for i in a:

if str(i) == str(val) :

r1='true'

if r1=='true':

print(val,' is found in the list')

elif r1=='false':

print(val,' is not found in the list')

l=input("Enter the list values:")

val=int(input("Enter the value to search:"))

a=l.split(',')

choise=input("Which type of search you want to use \n(a) Binary or (b) Linear:")

if choise == 'a':

binary()

elif choise =='b':

linear()

Output:
Ex.no-2

Sorting Doctors Details

Aim:

To write a python program using function to sort details of the doctors in


descending order of their specialization using bubble sort. The Doctors details include
DoctorID, Name and Specialization which is stored as nested list.

Program:

def bubble_sort(List):

for i in range(len(List)):

for j in range(len(List)-i-1):

if List[j][2] < List[j+1][2]:

List[j], List[j+1] = List[j+1],List[j]


repeat=1

List=[]

while repeat >0:

details=str(input("Enter the DoctorId, Name, Specialization:"))

details=list(details.split(","))

List.append(details)

cont=input("Do you want to continue(y/n):")

if cont == "y":

print(List)

continue

else:

bubble_sort(List)

print(List)

break

Output:
Ex.no-3

Sorting Product Details

Aim:

To write a python program which has the function to sort the detail of the product
in ascending order of their price using insertion sort. The nested list contain the details of
the product such as Pid, Pname, Qty and Price.

Program:

def insertion_sort(List):

for i in List:

j=List.index(i)

while j>0:

if int(List[j-1][3]) > int(List[j][3]):

List[j-1],List[j] =List[j], List[j-1]

else:
break

j=j-1

repeat=1

List=[]

while repeat >0:

details=str(input("Enter the Pid, Pname, Qty, Price:"))

details=list(details.split(","))

List.append(details)

print("Your data updated!!\n")

cont=input("Do you want to continue(y/n):")

if cont == "y":

continue

else:

insertion_sort(List)

print('Sorted list is ',List)

break

Output:
Ex.no-4

Display the words less than 4 characters in a Text file

Aim:

To Write a python program using functions to create a text file “Story.txt”, read lines
from the text file “Story.txt” and display those words whose length is less than 4 characters.

Program:

with open("story.txt") as f:

d=f.readlines()

a=''.join(d)

b=a.split('\n')

for i in b:

c=i.split(' ')

for j in range(len(c)):

if len(c[j]) < 4:
print(c[j])

Output:

Ex.no-5

Count the number of words starting with a vowel in a Text file

Aim:

To write a python program using function to count the number of words starting
with the vowel in the file “Book.txt”.

Program:

def find():

count=0

a=['a','e','i','o','u']

for i in d:

if i[0] in a:

count+=1
print(‘Number of words starting with vowel is:’,count)

with open('Books.txt') as f:

d=f.readlines()

find()

Output:

Ex.no-6

Display the lines which end with “healthy”

Aim:

To write a python program which has the function to read from the file “Exam.txt”
and display all the lines which ends with the word “health”.

Program:
def count():

for i in d:

a=''.join(i).split(' ')

if a[-1] == 'healthy':

print(i)

with open('Exam.txt') as f:

d=''.join(f.readlines()).split('\n')

count()

Output:
Ex.no-7

Write and Read a Binary file

Aim:

To write the car details, and read display the Toyota cars with price.

Program:

import pickle

def read():

with open("Cars.dat",'rb') as p:

d=pickle.load(p)

for i in d:

if i[1] == 'Toyato':

print('Price of Toyato car:',i[1],'-->',i[3])

while 1>0:

a=[]

no=int(input('Enter the Carno:'))

name=str(input('Enter the Car name:'))

mil=str(input('Enter the Mileage:'))

price=str(input('Enter the price of the car:'))

b=no,name,mil,price

a.append(b)

with open ("Cars.dat",'wb') as f:

pickle.dump(a,f)
choise=str(input('Do you want to continue or not(y/n):'))

if choise == 'y':

continue

elif choise == 'n':

read()

Output:

Ex.no-8

Updating Binary file

Aim:

To update the megapixel in the binary file by accepting the model number from
user.

Program:

import pickle
def show():

with open('mobile.dat','rb') as f:

dp=pickle.load(f)

print('Mobile records',dp)

global d

d=[]

d.append(dp)

def update():

with open('mobile.dat','wb') as k:

ans='false'

number=str(input('Enter the model number to update:'))

for i in range(len(d[0])):

if str(d[0][i][0]) == str(number):

mp=str(input('Enter the new megapixel:'))

d[0][i][2]=mp

ans='true'

print('Record updated')

if ans == 'false':

print('No such model number')

pickle.dump(d,k)

while 1>0:
choise=str(input('What do you want to do:\n(a)View records\n(b)Update
record\n>>>'))

if choise == 'a':

show()

elif choise == 'b':

update()

Output:

Ex.no-9

Deleting records from Binary file

Aim:

To Write, delete, read and count the number of records.

Program:
import pickle

def write():

d=[]

with open('telephone.dat','wb') as f:

name=input('Enter the name:')

address=input('Enter the address:')

areacode=input('Enter the areacode:')

ph_no=int(input('Enter the phone number'))

d.append([name,address,areacode,ph_no])

pickle.dump(d,f)

def delete():

d=[]

with open('telephone.dat','rb') as k:

d=pickle.load(k)

with open('telephone.dat','wb') as h:

found=False

val ='TP101'

d1=[]

for i in range(len(d)):

if d[i][2] != val:

d1.append(d[i])

pickle.dump(d1,h)

def read():
d=[]

with open('telephone.dat','rb') as k:

ans='y'

while True:

try:

d=pickle.load(k)

except EOFError:

break

for i in d:

print(i)

l=len(d)

print('The number of records:',l)

while 1>0:

choise=str(input('What do you want to do\n(a)Write\n(b)Delete\n(c)View\n>>> '))

if choise == 'a':

write()

elif choise == 'b':

delete()

elif choise == 'c':

read()
Output:

Ex.no-10

Write and Read CSV file

Aim:

To write the details of students in csv file and display the students whose average is
above 85.

Program:

import csv

r=True

def func():

with open("students.csv",'w',newline='') as f:

a=csv.writer(f)
a.writerow(val)

with open("students.csv") as f:

d=csv.reader(f)

for j in d:

if int(j[3]) > 85:

v.append(j)

v=[]

while r is True:

rno=int(input("Enter the Rool number:"))

name=str(input("Enter the student name:"))

marks=input("Enter the marks:")

avg=input("Average:")

val=[rno,name,marks,avg]

func()

choise=input("Do you want to continue(y/n): ")

if choise == 'y':

continue

else:

print('Students has 85 average are: ', v)

break

Output:
Ex.no-11

Write and Read CSV file(2)

Aim:

To write csv file and display the name and salary of the manager who belong to sales
department.

Program:

import csv

r=True

def func():

with open("emp.csv",'w',newline='') as f:

a=csv.writer(f)

a.writerow(val)
with open("emp.csv") as f:

d=csv.reader(f)

for j in d:

if j[3] == 'sales':

v.append([j[1],j[4]])

v=[]

while r is True:

eno=int(input("Enter your Eno:"))

name=str(input("Enter your name:"))

des=str(input("Enter your Designation:"))

dep=str(input("Enter your Department:"))

sal=int(input("Enter your salery:"))

val=[eno,name,des,dep,sal]

func()

choise=input("Do you want to continue(y/n): ")

if choise == 'y':

continue

else:

print('Managers belongs to sales departmet are: ', v)

Output:
Ex.no-12

Display sum of boundary, non-boundary, right and left diagonal of a nested list

Aim:

To write a python program to find the sum of the boundary, non-boundary, left and
right diagonal of a nested list A of size MxN.

Program:

def boundary():

Sum=0

for j in l[0]:

Sum=Sum+int(j)

for k in l[-1]:

Sum=Sum+int(k)

for m in l[1:-1] :

Sum=Sum+int(m[0]) +int(m[-1])
return Sum

def non_boundary():

Sum=0

for i in l[1:-1]:

for j in i[1:-1]:

Sum=Sum+int(j)

return Sum

def right_diagonal():

Sum=0

ans='y'

for i in l:

if len(i) != no:

ans='n'

break

if ans=='y':

p=-1

for i in l:

Sum=Sum+int(i[p])

p=p-1

return Sum

def left_diagonal():

Sum=0
ans='y'

for i in l:

if len(i) != no:

ans='n'

break

if ans =='y':

p=0

for i in l:

Sum=Sum+int(i[p])

p=p+1

if p > len(i):

break

return Sum

l=[]

no=int(input('Enter the number of rows:'))

for i in range(no):

a=str(input('Enter the row '+str(i)+' values with comma seperated:'))

l.append(a.split(','))

b=boundary()

nb=non_boundary()

rd=right_diagonal()

ld=left_diagonal()
print('Sum of Boundary is',b)

print('Sum of Non-Boundary is',nb)

print('Sum of Right-Diagonal is',rd)

print('Sum of Left-Diagonal is',ld)

Output:

Ex.no-13

Swapping and Palindrome in List

Aim:

To swap the elements in the list and to count the number of palindrome in the list.

Program:

def swap():
c=[]

b=len(a)

for j in range(b//2,b):

c.append(a[j])

for i in range(b//2):

c.append(a[i])

print('The swaped list is ',c)

def pal():

count=0

for i in a:

if i == i[::-1]:

count+=1

print('Number of palindrome elements in list is ',count)

l=str(input('Enter the list values with comma seperated:'))

a=l.split(',')

while 1>0:

choice=str(input("Do you what to:\n (a)Swap \n(b)Count palindrome\n>>>"))

if choice == 'a':

swap()

elif choice == 'b':

pal()

Output:
Ex.no-14

Stack

Aim:

To write a python program to do stack operations from the stack customers which
contains customer id,name,phone no.

Program:

def dopush():

cid=str(input('Cutomer ID:'))

name=str(input('Name:'))

no=str(input('Phone no:'))

b=cid,name,no

a.append(b)

print(a)

def dopop():
if a == []:

print("Stack is empty")

else:

a.pop()

def doshow():

if a == []:

print("Nothing in the stack")

else:

for i in a:

print('\nCustomer ID:',i[0])

print('Name:',i[1])

print('Phone no:',i[2])

a=[]

while 1>0:

choise=str(input('\nWhat do you want to do:\n(a)push\n(b)pop\n(c)display\n>>>'))

if choise == 'a':

dopush()

elif choise == 'b':

dopop()

elif choise == 'c':

doshow()

Output:
Ex.no-15

Queue

Aim:

To write a python program to add, delete, view from a queue Pasanger name, ticket-
no.

Program:

def InsQueue():

name=str(input('\nName:'))

ticketno=str(input('Ticket no:'))

b=name,ticketno

a.append(b)

def DelQueue():

if a == []:

print('Queue is empty')
else:

a.pop(0)

def DispQueue():

if a == []:

print('Queue is empty')

else:

for i in a:

print('Name :',i[0])

print('Ticket no:',i[1])

a=[]

while 1>0:

choise=str(input('\nWhat do you want to do:\n(a)Add\n(b)Delete\n(c)Details\n>>>'))

if choise == 'a':

InsQueue()

elif choise == 'b':

DelQueue()

elif choise == 'c':

DispQueue()

Output:

You might also like