You are on page 1of 19

INDEX

1.SORTING
2. TEXT FILES
3. CSV FILES
4. BINARY FILES
5. LIBRARY MANAGEMENT
5.STACKS AND QUEUES
6. SQL DATABASE
7. MYSQL CONNECTION
SORTING:
Q: BUBBLE SORT

l=[20,13,5,9,2,27,22,30]

n=len(l)
i=0
# bubble sort
for i in range(n-1):
for j in range(i+1,n):
if l[j]<l[i]:
tmp=l[i]
l[i]=l[j]
l[j]=tmp
print(l)

Q: INSERTIONS SORT
l=[20,13,5,9,2,27,22,30]
n=len(l)
i=0
# INSERT SORT
for i in range(1,len(l)):
sm=l[i]
j=i-1
while sm<l[j] and j>=0:
l[j+1]=l[j]
j=j-1
l[j+1]=sm

print(l)
Q: SELECTION SORT

def selection_sort(input_list):

for idx in range(len(input_list)):

min_idx = idx

for j in range( idx +1, len(input_list)):

if input_list[min_idx] > input_list[j]:

min_idx = j

# Swap the minimum value with the compared value

input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]

l=[20,13,5,9,2,27,22,30]
selection_sort(l)

print(l)

TEXT FILES
Question 1: Write Python code to store data in file.

# Open function to open the file "MyFile1.txt"

# (same directory) in append mode and

file1 = open("MyFile.txt","a")

# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2

file2 = open(r"D:\Text\MyFile2.txt","w+")
Question 2: Write a program to read and count character from data.txt file :

a)Character Upper/ Lower Character

b)Digit Character Characters/Symbol/ Spaces

c)Words/ Lines

d)Vowel /Consonant Character

a)f1=open("data.txt","r")

s=f1.read()

print(s)

count=0

for ch in s:

if ch.isupper()==True:

count+=1

print(count)

words=count+1 # After Space Count

print(words)

b) S=' '

f1=open("data.txt","r")

s=f1.read()

count=0
for ch in s:

if ch.isalnum()==False:

count+=1

print(count)

c)

f1=open("data.txt","r")

s=f1.read()

print(s)

words=s.split()

print(words,"",len(words))

f1=open("data.txt","r")

s=f1.readlines()

print(s)

print(s,"",len(s))

d)

f1=open("data.txt","r")

s=f1.read()

countV=0
countC=0

for ch in s:

if ch.isalnum()==True:

if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':

countV+=1

else:

countC+=1

print("V: ",countV,", C= ", countC)

Question 3 : Write a program to read and count Words start with from text file : Upper /Lower / Digits /
Special / Vowel / Consonant Character

f1=open("data.txt","r")

s=f1.read()

print(s)

words=s.split()

print(words,', ',len(words))

count=0
for word in words:

if word[0].isupper()==True:

count+=1

print(count)

Question 4: Write a program to read and count Words end with from text file : Upper /Lower / Digits /
Special / Vowel / Consonant/User Define Character

f1=open("data.txt","r")

s=f1.read()

print(s)

words=s.split()

print(words,', ',len(words))

count=0

for word in words:

if word[-1].isupper()==True:

count+=1

print(count)
Question 5: Write a program to count the word present in a text file DATA.TXT.

f1=open("data.txt","r")

s=f1.read()

print(s)

sword=input('Enter Your search Word: ')

words=s.split()

print(words,', ',len(words))

count=0

for word in words:

if word==sword:

count+=1

print(count)

CSV FILES

1) Write Python Functions to Create CSV file, Read file , Search file for a telephone directory.

import csv

def read_csv():
fp=open("tele.csv","r")

cs=csv.reader(fp)

for rec in cs:

if len(rec)>0:

print(rec[0],rec[1],rec[2])

fp.close()

def search_csv():

fp=open('tele.csv','r')

cs=csv.reader(fp)

name=input('Enter the name of the student whose phone number needs to be searched:')

for rec in cs:

if len(rec)>0:

if name==rec[1]:

print('Phone number:',rec[2])

break

else:

print('Not Found')

fp.close()

def write_csv():

fp=open("tele.csv","a")

cs=csv.writer(fp)

while True:

sno=int(input("Enter sno:"))

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

phno=str(input("Enter phone no:"))

tele=[sno,name,phno]

cs.writerow(tele)

rep=input("do you want to continue......y/n")


if rep in "nN":

break

fp.close()

2) Dictionary (dictwriter)

import csv
# my data rows as dictionary objects
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]

# field names
fl = ['name', 'branch', 'year', 'cgpa']

# writing to csv file


cf=open("urec.csv", 'w')
cwrt= csv.DictWriter(cf, fieldnames = fl)
cwrt.writeheader()
cwrt.writerows(mydict)
cf.close()

BINARY FILES

import pickle
def store():
bno=input("\n Enter bookno:")
bname=input("\n enter book name:")
sub=input("\n enter subject:")
noc=input("\n enter No of Copies:")
book=bno+":"+bname+":"+sub+":"+noc+"\n"
fp=open("books.txt","ab")
pickle.dump(book,fp)
fp.close()
def readfile():
fp=open("books.txt","rb")
while(1):
try:
print(pickle.load(fp))
except (EOFError):
break
fp.close()
readfile()

LIBRARY MANAGEMENT
import os
def insert():
fp=open("books.txt","a")
bno=input("\n Enter bookno:")
bname=input("\n enter book name:")
sub=input("\n enter subject:")
noc=input("\n enter No of Copies:")
book=bno+":"+bname+":"+sub+":"+noc+"\n"
fp.write(book)
fp.close()

def display():
fp=open("books.txt","r")
print("BookNo :Name :Subject :NoofCopies")
for rec in fp.readlines():
print(rec)
fp.close()
def search():
fp=open("books.txt","r")

bno=input("\n Enter Bookno:")


print("BookNo:Name:Subject:NoofCopies")
for rec in fp.readlines():
row=rec.split(":")
bn=row[0]
if bn==bno:
print(rec)
fp.close()
def delt():
fp=open("books.txt","r")
tmp=open("temp.txt","w")
bno=input("\n Enter Bookno to be deleted:")
for rec in fp.readlines():
row=rec.split(":")
bn=row[0]
if bn!=bno:
tmp.write(rec)
fp.close()
tmp.close()
os.remove("books.txt")
os.rename("temp.txt","books.txt")
def upd():
fp=open("books.txt","r")
tmp=open("temp.txt","w")
bno=input("\n Enter Bookno to be updated:")
for rec in fp.readlines():
row=rec.split(":")
bn=row[0]
if bn==bno:
bname=input("\n enter book name:")
sub=input("\n enter subject:")
noc=input("\n enter No of Copies:")
book=bno+":"+bname+":"+sub+":"+noc+"\n"
tmp.write(book)
else:
tmp.write(rec)
fp.close()
tmp.close()
os.remove("books.txt")
os.rename("temp.txt","books.txt")
ch=0
while(ch!=6):
print("******** Library Management System*******")
print("\n")
print("1. Insert Record")
print("2. Display Record")
print("3. Search Record")
print("4. Modify Record")
print("5. Delete Record")
print("6. Exit")
print("\nYour ch..1-6")
ch=int(input("\n your ch...."))
if ch==1:
insert()
elif ch==2:
display()
elif ch==3:
search()
elif ch==4:
upd()
elif ch==5:
delt()
STACKS
Q: Basic functions of stacks- push pop peek display

stk=[]
top=-1
def PUSH(stk,student):
stk.append(student)
top=len(stk)-1

def display(stk):
if stk==[]:
print("underflow")
return
top=len(stk)-1
for i in range(top,-1,-1):
print(stk[i])
def popp(stk):
if stk==[]:
print("underflow")
return
top=len(stk)-1
print("Values to be popped are....")
print(stk[top])
stk.pop()
def peek(stk):
if stk==[]:
print("underflow")
return
top=len(stk)-1
print(stk[top])

ch=0
while ch!=5:
print("1. push")
print("2. display")
print("3. pop")
print("4. peek")
print("5. Exit")
ch=int(input("Enter ch...."))
if ch==1:
sno=int(input("Enter student No:"))
sn=input("Enter student Name:")
data=[sno,sn]
PUSH(stk,data)
elif ch==2:
display(stk)
elif ch==3:
popp(stk)
elif ch==4:
peek(stk)

Q: Basic functions of queues: enqueue, dequeue, peek, display:

que=[]
rear=-1
front=-1
def enqueue(que, client):
que.append(client)
front=0
rear=len(que)-1

def display(que):
if que==[]:
print("underflow")
return
front=0
rear=len(que)-1
for i in range(front,rear+1):
print(que[i])
def dequeue(que):
if que==[]:
print("underflow")
return
front=0
rear=len(que)-1
print("Values to be removed are....")
print(que[front])
que.pop(0)
def peek(que):
if que==[]:
print("underflow")
return
front=0
rear=len(que)-1
print(que[front])

ch=0
while ch!=5:
print("1. enqueue")
print("2. display")
print("3. dequeue")
print("4. peek")
print("5. Exit")
ch=int(input("Enter ch...."))
if ch==1:
sno=int(input("Enter client No:"))
cn=input("Enter client Name:")
data=[sno,cn]
enqueue(que,data)
elif ch==2:
display(que)
elif ch==3:
dequeue(que)
elif ch==4:
peek(que)
SQL DATABASE

CREATING AND INSERTING TABLE

Create table personalinfo


(
Empno char(4) primary key check(empno like “E%”),
Name char(25) not null,
Mobileno char(10) not null,
Address varchar2(100) not null,
Dob date not null,
Doj date not null,
Design char(10) not null,
Deptno number(2) references departinfo,
Pfno number(2) unique
);
Create table departinfo
(
Deptno number(2) primary key,
dname char(15) not null,
loc char(10)
);
Insert into departinfo values(10,”Finance”,”Delhi”);
Insert into departinfo values(20,”HRD”,”Banglore”);
Insert into
personalinfo(‘E1’,’AUDRIK’,’6467474’,’DELHI’,’20-AUG-
2003’,’20-JUL-2020’,’MANAGER’,20,62562);

PYTHON-MYSQL CONNECTIVITY

1) READ TABLE-FETCH ONE

import mysql.connector as mc

mydb=mc.connect(host="localhost",user="root",passwd="root@123",database="student")

cur=mydb.cursor()

cur.execute("select * from stud_info")


rows=cur.fetchall()

for rec in rows:

if rec[2]=="Delhi":

print(rec[0],rec[1],rec[2])

2) READ TABLE-INSERT

import mysql.connector

db=mysql.connector.connect(host="localhost",user="root",passwd="root@123",database="student")

cur=db.cursor()

rep="y"

while rep=="y":

rno=input("Enter rollno:")

name=input("Enter Name:")

addr=input("Enter address:")

cmd="INSERT INTO stud_info(rno,name,addr)VALUES({},'{}','{}')".format(rno,name,addr)

cur.execute(cmd)

db.commit()

rep=input("Enter more frecords....y/n.?")

db.close()

3) READ TABLE-UPDATE

import mysql.connector

db=mysql.connector.connect(host="localhost",user="root",passwd="root@123",database="student")

cur=db.cursor()

rno=input("Enter rollno for the student whose record to be updated:")

adr=input("New address:")

cmd = """update stud_info set addr=%s where rno=%s"""

data=(adr,rno)

cur.execute(cmd, data)
db.commit()

db.close()

4) READ TABLE-DELETE

import mysql.connector

db=mysql.connector.connect(host="localhost",user="root",passwd="root@123",database="student")

cur=db.cursor()

rno=input("Enter rollno for the student whose record to be deleted:")

sql_Delete_query = """Delete from stud_info where rno = %s"""

cur.execute(sql_Delete_query, (rno,))

db.commit()

db.close()

You might also like