0% found this document useful (0 votes)
16 views10 pages

Quiz 2 Questions

The document contains a series of Python programming exercises focusing on data structures, user-defined functions, and file handling. It includes tasks such as manipulating lists and stacks, reading and writing to CSV files, and processing text files for specific outputs. Each exercise is accompanied by example data and expected outputs to guide implementation.

Uploaded by

yixix44532
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)
16 views10 pages

Quiz 2 Questions

The document contains a series of Python programming exercises focusing on data structures, user-defined functions, and file handling. It includes tasks such as manipulating lists and stacks, reading and writing to CSV files, and processing text files for specific outputs. Each exercise is accompanied by example data and expected outputs to guide implementation.

Uploaded by

yixix44532
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
You are on page 1/ 10

DAP: Data Structures using python [Quiz II]

1. A list, NList contains following record as list elements: [City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user
defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object
containing name of the city and country, which are not in India and distance is less than
3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function
should display “Stack Empty” when there are no elements in the stack.

For example: If the nested list contains the following data:


NList=[["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE",
2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka",
3405]]

The stack should contain: ['Naypyidaw', 'Myanmar'], ['Dubai', 'UAE'], ['Columbo', 'Sri Lanka']

The output should be: ['Columbo', 'Sri Lanka'] ['Dubai', 'UAE'] ['Naypyidaw', 'Myanmar']
Stack Empty

travel=[]
def Push_element(NList):
for L in NList:
if L[1]!="India" and L[2]<3500:
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print("Stack Empty")
NList=[["New York","U.S.A",11734],
["Naypyidaw","Myanmar",3219],
["Dubai","UAE",2194],
["London","England",6693],
["Gangtok","India",1580],
["Colombo","SriLanka",3405]]

Push_element(NList)
print(travel)
Pop_element()

2. A list contains the following record of customer:


[Customer_name, Room Type]
Write the following user-defined functions to perform given operations on the stack named
‘ Hotel’:
i) Push_Cust () – To Push customers names of those customers who are staying in Delux’
Room Type.
ii) Pop_Cust ()- To Pop the names of customers from the stack and display them. Also,
display “Underflow” when there are no customers in the stack.
For example:
If the lists with customer details are as follows:
[“Ram”, “Delux”]
[“Balaram”, “Standard”]
[“Abinash”, “Delux”]
The stack should contain
Abinash
Ram
Underflow

customer=[["Ram", "Delux"], ["Balaram", "Standard"],


["Abinash", "Delux"]]
hotel=[]
def push_cust():
for i in customer:
if i[1]=='Delux':
hotel.append(i[0])
return hotel
def pop_cust():
if hotel==[]:
return "Underflow"
else:
return hotel.pop()
push_cust()
while True:
if hotel==[]:
print(pop_cust())
break
else:
print(pop_cust())

3. Write a function in Python, Push (Vehicle) where, Vehicle is a dictionary containing details
of vehicles – {Car_Name: Maker}.
The function should push the name of car manufactured by “TATA’ (including all the
possible cases like Tata, TaTa, etc.) to the stack.
For example:
If the dictionary contains the following data:
Vehicle={“Santro” : “Hyundai”, “Nexon”: “TATA”, “Safari” : “Tata”}
The stack should contain
Safari
Nexon
Vehicle={"Santro" : "Hyundai", "Nexon": "TATA",
"Safari" : "Tata"}
stk=[]
def push(vehicle):
for i in vehicle:
if vehicle[i].lower()=='tata':
stk.append(i)
return stk

push(Vehicle)
for i in range(-1,-len(stk)-1,-1):
print(stk[i])

4. What possible output(s) are expected to be displayed on screen at the time of


execution of the following program:

import random
M=[5,10,15,20,25,30]
for i in range(1,3):
first=random.randint(2,5)-1
sec=random.randint(3,6)-2
third=random.randint(1,4)
print (M[first],M[sec],M[third],sep="#")

i)10#25#15
20#25#25
ii) 5#25#20
25#20#15
iii) 30#20#20
20#25#25
iv) 10#15#25#
15#20#10#

Hint:
import random
print(random.randint(3, 9))
#returns a number between 3 and 9 (both included)

5. Write a program in Python that defines and calls the following user-defined functions :
i) Add_Book(): Takes the details of the books and adds them to a csv file ‘Book.csv‘. Each record consists of a list with field
elements as book_ID, B_ name and pub to store book ID, book name and publisher respectively.
ii) Search_Book(): Takes publisher name as input and counts and displays the number of books published by them.
import csv
def Add_Book():
f=open("book.csv","a",newline='')
wo=csv.writer(f)
book_id=input("Enter Book ID:")
b_name=input("Enter Book Name:")
pub=input("Enter Publisher:")
wo.writerow([book_id,b_name,pub])
f.close()

def Search_Book():
f=open("book.csv",'r')
ro=csv.reader(f)
pn=input("Enter Publisher:")
cnt=0
for i in ro:
if i[2]==pn:
cnt+=1
print("Book ID:",i[0])
print("Book:",i[1])
print("Publisher:",i[2])
print("Total Books Published by ",pn," are:",cnt)
Add_Book()
Search_Book()

6. Write a program in Python that defines and calls the following user-defined functions:

1. COURIER_ ADD(): It takes the values from the user and adds the details to a csv file ‘courier.csv’. Each record
consists of a list with field elements as a cid, s_name, Source and destination to store Courier ID, Sender name,
Source and destination address respectively.
2. COURIER_SEARCH (): Takes the destination as the input and displays all the courier records going to that
destination.

import csv
def COURIER_ADD():
f=open("courier.csv","a",newline='')
wo=csv.writer(f)
cid=input("Enter Courier ID:")
s_name=input("Enter Sender Name:")
source=input("Enter Source:")
destination=input("Enter Destination:")
wo.writerow([cid,s_name,source,destination])
f.close()

def COURIER_SEARCH():
f=open("courier.csv",'r')
ro=csv.reader(f)
de=input("Enter desitination:")
for i in ro:
if i[3]==de:
print("Courier ID:",i[0])
print("Sender:",i[1])
print("Source:",i[2])
print("Destination:",i[3])
COURIER_ADD()
COURIER_SEARCH()
7. Write a function EOReplace() in Python, which accepts a list L of numbers. Thereafter, it increments all even
numbers by 1 and decrements all odd numbers by 1.

def EOReplace(L):
for i in range(len(L)):
if L[i]%2!=0:
L[i]-=1
else:
L[i]+=1
return L
L=eval(input("Enter List:"))
print(EOReplace(L))

8. Write the definition of a Python function named LongLines( ) which reads the contents of a text file named ‘LINES .
TXT’ and displays those lines from the file which have at least 10 words in it.

For example, if the content of ‘ LINES . TXT ‘ is as follows : 3

Once upon a time, there was a woodcutter

He lived in a little house in a beautiful, green wood.

One day, he was merrily chopping some wood.

He saw a little girl skipping through the woods, whistling happily.

The girl was followed by a big gray wolf.

Then the function should display output as :

He lived in a little house in a beautiful, green wood.

He saw a little girl skipping through the woods, whistling happily.

def LongLines():
f=open("lines.txt")
dt=f.readlines()
for i in dt:
if len(i.split())>10:
print(i)
f.close()
LongLines()
9. Write a function count Dwords ( ) in Python to count the words ending with a digit in a text file ” Details . txt”.

Example:

If the file content is as follows :

On seat2 VIP1 will sit and

On seat1 VVIP2 will be sitting

Output will be:

Number of words ending with a digit are 4

def Dwords():
f=open("details.txt")
dt=f.read()
w=dt.split()
c=0
for i in w:
if i[-1].isdigit():
c+=1
print("Number of words ending with digit are:",c)
Dwords()

10. Write the output.

def short_sub(lst,n):
for i in range(0,n):
if len(lst[i])>2:
lst[i]=lst[i]+lst[i]
else:
lst [i]=lst[i]
subject=['DAP','DMSC','AIML','CD','WT']
short_sub(subject,5)
print(subject)

11. Write a function COUNT() in Python to read from a text file 'Gratitude.txt' and display the count
of the letter 'e' in each line Example: If the file content is as follows:

Gratitude is a humble heart's radiant glow,


A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
The COUNT() function should display the output as:
Line 1 : 3
Line 2 : 4
Line 3 : 6
Line 4 : 1
def Count():
F=open('details.txt')
T=F.readlines()
X=1
for i in T:
print('Line',X,':',i.count('e'))
X=X+1
F.close()
Count()

12. Write a function Start_with_I() in Python, which should read a text file 'Gratitude.txt' and then
display lines starting with 'I'. Example: If the file content is as follows:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
Then the output should be
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.

def Start_with_I():
F=open('details.txt')
T=F.readlines()
for i in T:
if i[0]=='I':
print(i,end='')
F.close()
Start_with_I()

13. Given a Dictionary Stu_dict containing marks of students for three test-series in the form
Stu_ID:(TS1, TS2, TS3) as key-value pairs. Write a Python program with the following user-defined
functions to perform the specified operations on a stack named Stu_Stk

(i) Push_elements(Stu_Stk, Stu_dict) : It allows pushing IDs of those students, from the dictionary
Stu_dict into the stack Stu_Stk, who have scored more than or equal to 80 marks in the TS3 Test.

(ii) Pop_elements(Stu_Stk): It removes all elements present inside the stack in LIFO order and prints
them. Also, the function displays 'Stack Empty' when there are no elements in the stack. Call both
functions to execute queries.

For example: If the dictionary Stu_dict contains the following data: Stu_dict ={5:(87,68,89),
10:(57,54,61), 12:(71,67,90), 14:(66,81,80), 18:(80,48,91)}

After executing Push_elements(), Stk_ID should contain [5,12,14,18]

After executing Pop_elements(), The output should be: 18 14 12 5 Stack Empty


Stu_dict={5:(87,68,89), 10:(57,54,61),
12:(71,67,90),14:(66,81,80), 18:(80,48,91)}
Stu_Stk=[]
def Push_elements(Stu_Stk, Stu_dict):
for Stu_ID, marks in Stu_dict.items():
if marks[2]>=80:
Stu_Stk.append(Stu_ID)
def Pop_elements(Stu_Stk):
while len(Stu_Stk)>0:
print(Stu_Stk.pop())
if not Stu_Stk:
print('Stack Empty')
Push_elements(Stu_Stk, Stu_dict)
Pop_elements(Stu_Stk)

14. Create a function maxsalary() in Python to read all the records from an already existing file
record.csv which stores the records of various employees working in a department. Data is stored
under various fields as shown below:

Function should display the row where the salary is maximum. Note: Assume that all employees
have distinct salary.

import csv
def maxsalary():
f=open('record.csv', 'r')
reader=csv.reader(f)
skip_header = True
max= 0
for row in reader:
if skip_header:
skip_header = False
else:
if(int(row[3])>max):
max=int(row[3])
rec=row
print('Row with the highest salary : ', rec)
f.close()
maxsalary()
15. Write a Python Program to display alternate characters of a string my_str.

For example, if my_str = "Computer Science" The output should be Cmue cec

my_str = "Computer Science"


alternate_chars = my_str[::2]
print(alternate_chars)

16. What will be the output of the following code?

L = [5,10,15,1]
G=4
def Change(X):
global G
N=len(X)
for i in range(N):
X[i] += G
Change(L)
for i in L:
print(i,end='$')

17. Write a function dispBook(BOOKS) in Python, that takes a dictionary BOOKS as an argument and
displays the names in uppercase of those books whose name starts with a consonant.
For example, Consider the following dictionary
BOOKS = {1:"Python", 2:"Internet Fundamentals ", 3:"Networking ", 4:"Oracle sets",
5:"Understanding HTML"}
The output should be:
PYTHON
NETWORKING

def dispBook(BOOKS):
for key in BOOKS:
if BOOKS[key][0] not in "AEIOUaeiou":
print(BOOKS[key].upper())
BOOKS = {1:"Python",2:"Internet Fundamentals
",3:"Networking",4:"Oracle sets",5:"Understanding
HTML"}
dispBook(BOOKS)

18. Write a Python Program containing a function FindWord(STRING, SEARCH), that accepts two
arguments : STRING and SEARCH, and prints the count of occurrence of SEARCH in STRING. Write
appropriate statements to call the function.
For example, if STRING = "Learning history helps to know about history with interest in history" and
SEARCH = 'history', the function should display
The word history occurs 3 times.

def FindWord(STRING,SEARCH):
return (STRING.count(SEARCH) )
str = "Learning history helps to know about history
with interest in history"
word = input('Enter word to search : ')
print('The word', word, 'occurs', FindWord(str,word),
'times')

19. Find output ?

L=["One , Two","Three","Four"]
print(len(L)/2*len(L[0]))

20. Find output ?

print("Welcome To My Blog"[2:6] + "Welcome To My


Blog"[5:9])

You might also like