0% found this document useful (0 votes)
5 views25 pages

Python Functions for List and File Operations

The document contains a series of programming tasks and solutions primarily in Python, covering various functions such as altering lists, sorting algorithms, and file handling. It also includes SQL commands for database operations related to student and furniture tables. Each task is numbered and provides both the problem statement and the corresponding code solution.

Uploaded by

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

Python Functions for List and File Operations

The document contains a series of programming tasks and solutions primarily in Python, covering various functions such as altering lists, sorting algorithms, and file handling. It also includes SQL commands for database operations related to student and furniture tables. Each task is numbered and provides both the problem statement and the corresponding code solution.

Uploaded by

raghavkhera1912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SNO. PROGRAM T.

SIGN

1 Write the de nition of a function Alter(A, N) in python,


which should change all the multiples of 5 in the list to
5 and rest of the elements as 0.

2 Write code for a function void oddEven (s,


N) in python, to add 5 in all the odd
values and 10 in all the even values of the
list 5
3 Write a code in python for a function
Convert ( T, N) , which repositions
all the elements of array by shifting each
of them to next position and shifting first
element to last position.

4 Write a function CHANGEO ,which accepts an


list of integer and its size as parameters
and divide all those list elements by 7
which are divisible by 7 and multiply list
elements by 3.

5 Write a Get2From1( ) function in to


transfer
the content from one list ALL[ ] to two
list
Odd[ ]and Even[].
The Even should contain values from places
(0,2,4,………) of ALL[] and Odd[]
should contain values from places
( 1,3,5,……….).

6 Write a definition for function SHOWINFO()


to read each record of a binary file
[Link],
([Link]- id,gift,cost).Assume that info
is stored in the form of dictionary
fi
SNO. PROGRAM [Link]

7 Write a definition for function COSTLY() to


read each record of a binary file
[Link], find and display those items,
which are priced less than 50.
([Link]- id,gift,cost).Assume that info
is stored in the form of dictionary

8 find the no of lines in [Link]?

9 Write a program that reads character from


the keyboard one by one. All lower case
characters get store inside
the file LOWER, all upper case characters
get stored inside the file UPPER and all
other characters get stored
inside OTHERS.

10 Write a definition for function COSTLY() to


read each record of a binary file
[Link], find and display those items,
which are priced between 50 to 60.
([Link]- id,gift,cost).Assume that info
is stored in the form of list

11 Write a program to bubble sort a particular


list in ascending order.
12 Write a program to sort a particular list
in ascending order in insertion sort method
13 Write a function in python to perform a
DELETE operation in a dynamically allocated
queue considering the following
description:U,V
SNO. PROGRAM [Link]

14 A linear stack called "List" contains the


following information:

a. Roll Number of student


b. Name of student

Write add(List) and pop(List) methods in


python to add and remove from the stack
15 Write a function QUEDEL( ) in python to
display and delete an element from a
dynamically allocated Queue containing
information of the following given
structure:Itemno , Itemname
16 Write SQL commands for (b) to (e) and
write the outputs for (f) on the basis of
table GRADUATE
17 Given the following tables for a database
FURNITURE :
18 .Answer the questions (a) and (b) on the
basis of the following tables SHOPPE and
ACCESSORIES.
19 Write a MySQL-Python connectivity code display company
name, product name, customername, price and qty, which
are common in both the tables COMPANY and
CUSTOMER. Database name is “org”

20 Write a MySQL-Python connectivity to retrieve data, one


record at a time, from city table for employees with id less
than 10.

PROGRAMS
#1: Write the de nition of a function Alter(A, N) in
python, which should change all the multiples of 5 in the
list to 5 and rest of the elements as 0.
#sol

def Alter ( A, N):


for i in range(N):
if(A[i]%5==0):
A[i]=5
else:
A[i]=0
print("LIst after Alteration", A)

d=[10,14,15,21]
print("Original list",d)
r=len(d)
Alter(d,r)

'''
OUTPUT

Original list [10, 14, 15, 21]


LIst after Alteration [5, 0, 5, 0]
'''

#2: Write code for a function void oddEven


(s, N) in python, to add 5 in all the odd
fi
values and 10 in all the even values of the
list 5.

#sol
def oddEven ( s, N):
for i in range(N):
if(s[i]%2==0):
s[i]=s[i]+5
else:
s[i]=s[i]+10
print("LIst after Alteration", s)

d=[10,13,15,21]
print("Original list",d)
r=len(d)
oddEven(d,r)
'''

output
Original list [10, 13, 15, 21]
LIst after Alteration [15, 23, 25, 31]

#3: Write a code in python for a function


Convert ( T, N) , which repositions
all the elements of array by shifting each
of them to next position and shifting first
element to last position.
e.g. if the content of array is
0 1 2 3
10 14 11 21
The changed array content will be:
0 1 2 3
14 11 21 10
‘''

def Convert ( T, N):


t=T[0]
for i in range(N-1):
T[i]=T[i+1]
T[N-1]=t
print("after conversion",T)

d=[10,14,11,21]
print("Original List",d)
r=len(d)
Convert(d,r)
'''
output

Original List [10, 14, 11, 21]


after conversion [14, 11, 21, 10]

#4: Write a function CHANGEO ,which accepts


an list of integer and its size as
parameters and divide all those list
elements by 7 which are divisible by 7 and
multiply list elements by 3.

sol:
def CHANGEO(A,S):
for i in range(S):
if(A[i]%7==0):
A[i]=A[i]/7
else:
A[i]=A[i]*3
print("after change",A)

#calling
d=[12,34,56,7,89,21]
print("original list",d)
r=len(d)
CHANGEO(d,r)
'''
output

original list [12, 34, 56, 7, 89, 21]


after change [36, 102, 8.0, 1.0, 267, 3.0]

#5: Write a Get2From1( ) function in to


transfer
the content from one list ALL[ ] to two list
Odd[ ]and Even[].
The Even should contain values from places
(0,2,4,………) of ALL[] and Odd[]
should contain values from places
( 1,3,5,……….).
'''

even=[]
odd=[]
def fun(all,s):
for i in range(0,s-1):
if(i%2==0):
[Link](all[i])
else:
[Link](all[i])

print("even list",even)
print("odd list",odd)

d=[2,4,1,6,5,7,9,23,10]
print("actual list",d)
s=len(d)
fun(d,s)
'''
OUTPUT:

actual list [2, 4, 1, 6, 5, 7, 9, 23, 10]


even list [2, 1, 5, 9]
odd list [4, 6, 7, 23]
‘''

#6: Write a definition for function


SHOWINFO() to read each record of a binary
file
[Link],
([Link]- id,gift,cost).Assume that info
is stored in the form of dictionary
'''
#Sol:
import pickle
def SHOWINFO():
f=open("[Link]","rb")
while True:
try:
g=[Link](f)
print(g)
except:
break
[Link]()

#7: Write a definition for function COSTLY()


to read each record of a binary file
[Link], find and display those items,
which are priced less than 50.
([Link]- id,gift,cost).Assume that info
is stored in the form of dictionary

#sol
def COSTLY():
f=open("[Link]","rb")
while True:
try:
r=[Link](f)
if(r['cost']<50):
print(r)
except:
break
[Link]()

#8: find the no of lines in [Link]?

f=open(r"C:
\Users\hp\Desktop\cs\networking\[Link]
")
t=[Link]()
print(len(t))
#9: Write a program that reads character
from the keyboard one by one. All lower case
characters get store insidethe file LOWER,
all upper case characters get stored inside
the file UPPER and all other characters get
stored
inside OTHERS.

ANS.
f=open("[Link]")
f1=open("[Link]","a")
f2=open("[Link]","a")
f3=open("[Link]","a")

r=[Link]()

for i in r:
if(i>='a' and i<='z'):
[Link](i)
elif(i>='A' and i<='Z'):
[Link](i)
else:
[Link](i)

[Link]()
[Link]()
[Link]()
[Link]()
#10: Write a definition for function
COSTLY() to read each record of a binary
file
[Link], find and display those items,
which are priced between 50 to 60.
([Link]- id,gift,cost).Assume that info
is stored in the form of list

#sol
def COSTLY():
f=open("[Link]","rb")
while True:
try:
r=[Link](f)
if(r[2]>=50 and r[2]<=60):
print(r)
except:
break
[Link]()

#11 Write a program to bubble sort a


particular list in ascending order.

Ans.
d=[34,67,9,6,23,15]
n=len(d)
for i in range(n):
for j in range(n-i-1):
if(d[j]>d[j+1]):
d[j],d[j+1]=d[j+1],d[j]
print(d)
#12 Write a program to sort a particular
list in ascending order in insertion sort
method.

Ans.
d=[23,45,14,27,18]
n=len(d)
for i in range(1,n):
a=d[i]
j=i-1
while (j>=0 and a<d[j]):
d[j+1]=d[j]
j=j-1
d[j+1]=a
print(d)

#13 Write a function in python to perform a


DELETE operation in a
dynamically allocated queue considering the
following description:
U,V
Ans.
queue=[]
rear=front=-1
def DELETE ():
ql=len(queue)
if(ql<=0):
print(“queue empty”)
else:
rear=rear-1
U , V=[Link](0)
print(“deleted”,U, V)

#14: A linear stack called "List" contains


the following information:

a. Roll Number of student


b. Name of student

Write add(List) and pop(List) methods in


python to add and remove from the stack.

[Link]=[]
def add(List):
rno=int(input("Enter roll number"))
name=input("Enter name")
item=[rno,name]
[Link](item)
def pop(List):
if len(List)>0:
[Link]()
else:
print("Stack is empty")

def disp(s):
if(s==[]):
print("list is empty")
else:
top=len(s)-1
print(s[top],"---top")
for i in range(top-1,-1,-1):
print(s[i])

#Call add and pop function to verify the


code
add(List)
add(List)
disp(List)
pop(List)
disp(List)

#OUTPUT
Enter roll number 1
Enter name reena
Enter roll number 2
Enter name teena
[2, 'teena'] ---top
[1, 'reena']
[1, 'reena'] ---top

#[Link] a function QUEDEL( ) in python to


display and delete an element
from a dynamically allocated Queue
containing information of the following
given structure:
Itemno , Itemname

Ans
queue=[]
rear=front=-1
def QUEDEL ():
ql=len(queue)
if(ql&lt;=0):
print(“queue empty”)
else:
rear=rear-1
Itemno , Itemname=[Link](0)
print(“deleted”,Itemno, Itemname)

#16 Write SQL commands for (b) to (e) and


write the outputs for (f) on the basis of
table
GRADUATE.

a. List the names of those students who have


obtained DIV 1 sorted by NAME.
b. Display a report, listing NAME, STIPEND,
SUBJEZCT and amount of stipend
received in a year assuming that the STIPEND
is paid every month.
c. To count the number of students who are
either PHYSICS or COMPUTER SC
graduates.
d. To insert a new row in the GRADUATE
table:
11, “KAJOL”, 300, “COMPUTER SC”, 75, 1
e. Give the output of following SQL
statement based on table GRADUATE:
I. Select MIN(AVERAGE) from GRADUATE where
SUBJECT= “PHYSICS”;
II. Select SUM(STIPEND) from GRADUATE where
DIV=2;
III. Select AVG(STIPEND) from GRADUATE where
AVERAGE&gt;=65;
IV. Select COUNT(distinct SUBJECT) from
GRADUATE;

ANS:(a) Select Name From GRADUATE


Where DIV = 1
Order by Name;
(b) Select Name, stipend, subject, stepend *
12

From GRADUATE

(c) Select count (*)From GRADUATE


Where subject IN (“PHYSICS”, “COMPUTER SC”);

(d) Insert into GRADUATEValues (11, “KAJOL”,


300, “COMPUTER SC”, 75, 1);
(e) (i) 63 (ii) 1000 (iii) 450 (iv) 4
#[Link] the following tables for a
database FURNITURE :
NOTE: Write SQL command for (a) to (f) and
write the outputs for (g) on the bases of
tables
FURNITURE AND ARRIVALS.

a. To show all information about the baby


cots from the FURNITURE table.

b. To list the ITEMNAME which are priced at


more than 15000 from the FURNITURE
table.

c. To list ITEMNAME AND TYPE of those items,


in which DATEOFSTOCK is before
22/01/02 from the FURNITURE table in
descending order of ITEMNAME.
d. To display ITEMNAME and DATEOFSTOCK of
those items, in which the DISCOUNT
percentage is more than 25 from FURNITURE
table.

e. To count the number of items, whose TYPE


is “Sofa” from FURNITURE table.

f. To insert a new row in the ARRIVALS table


with the following data:
14, “Velvet touch”, Double
bed”, {25/03/03}, 25000, 30

ANSWER:
(a) Select * From FURNITURE Where TYPE =
“Baby cot”;

(b) Select ITEMNAME From FURNITURE Where


PRICE &gt; 15000;

(c) Select ITEMNAME, TYPE From FURNITURE


Where DATEOFSTOCK &lt; {22/01/02} Order by
ITEMNAME;

(d) Select ITEMNAME, DATEOFSTOCK From


FURNITURE Where DISCOUNT
&gt; 25.

(e) Select Count (*) From FURNITURE Where


TYPE = “Sofa”;

(f) Insert Into ARRIVALS Values (14, “Velvet


touch”, “Double bed”, {25/03/03}, 25000,
30);
#[Link] the questions (a) and (b) on the
basis of the following tables SHOPPE and
ACCESSORIES.

Write the SQL queries:


(i) To display Name and Price of all the
accessories in ascending order of their
Price.
(ii) To display Id and SName of all Shoppe
in Nehru Place.
(iii) To display Minimum and Maximum Price
of each Name of accessories.
(iv) To display Name, Price of all
accessories and their respective SName
where they are available.
b. (i) SELECT DISTINCT Name FROM ACCESSORIES
WHERE Price&gt;=500;
(ii) SELECT Area, COUNT (*) FROM GROUP BY
Area;

(iii) SELECT COUNT (DISTINCT Area) FROM


SHOPPE;
(iv) SELECT Name, Price*0.05 DISCOUNT FROM
ACCESSORIES WHERE SNo
IN (‘S02, ‘S03’);

ANSWER:(a) (i) SELECT Name, Price


FROM ACCESSORIES
ORDER BY Price ASC;

(ii) SELECT ID, Price


FROM SHOPPE
WHERE Area = ‘Nehru Place’;

(iii) SELECT MIN (Price) “Minimum


Price”,
MAX (Price) “Maximum Price”,
Name
FROM ACCESSORIES
GROUP BY Name;
(iv) SELECT Name, Price, SName
FROM ACCESSORIES A. SHOPPE S
WHERE A. ID = S. ID

(b) (i)

NAME
Mother Board
Hard Disk
LCD

(ii)

AREA COUNT(*)
CP 2
GK II 1
Nehru Place 2

(iii) COUNT (DISTINCT Area)3


#[Link] a MySQL-Python connectivity code display
company name, product name, customername, price and qty,
which are common in both the tables COMPANY and
CUSTOMER. Database name is “org”

ANSWER:

Import [Link] as m
db=[Link](host=“localhost”.user=“root”,passwd=“1234”,d
atabase=“org”
cursor=[Link]()
[Link](“select name, price,qty from
company,customer where [Link]=[Link]
data=[Link]()
For i in data:
Print (i)
[Link]
#20. Write a MySQL-Python connectivity to retrieve data, one
record at a time, from city table for employees with id less
than 10.

ANSWER:

Import [Link] as m
db=[Link](host=“localhost”.user=“root”,passwd=“1234”,d
atabase=“school”
c=[Link]()
[Link](“select*from amp where id<10”
r=[Link]()
For i in r :
Print (i)

You might also like