[go: up one dir, main page]

0% found this document useful (0 votes)
396 views65 pages

Computer Science Stack Operations Support Material

Computer science question
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)
396 views65 pages

Computer Science Stack Operations Support Material

Computer science question
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/ 65

KENDRIYA VIDYALAYA SANGATHAN, RANCHI

SUPPORT MATERIAL FOR BRIGHT STUDENTS

SUBJECT: COMPUTER SCIENCE (083)

Total: 145 Question

Data Structure(Stack)

Q1. Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a
player by considering them as push and pop operations in a stack.

Answer:
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()

Q2. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:

1. Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value (marks) is greater than 70.
2. Pop and display the content of the stack.

The dictionary should be as follows:

d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}

Then the output will be: Umesh Vishal Ishika

Answer:
def push(stk,item):
stk.append(item)

def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)

while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break

Q3. Write a function in Python PUSH(Num), where Num is a list of integer numbers. From this list
push all positive even numbers into a stack implemented by using a list. Display the stack if it has
at least one element, otherwise display appropriate error message.

Answer:
def PUSH(Num):
s=[]
for x in Num:
if x%2==0 and x>0:
s.append(x)
if len(s)==0:
print("STACK EMPTY")
else:
print(s)

Q4. Write a function in Python POP(cities), where cities is a stack implemented by a list of city
names for eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’]. The function returns the value deleted
from the stack.

Answer:

def POP(cities):
#For empty stack
if(len(cities)==0):
print("Under flow")
else:
l=len(cities)
c=cities[l-1]
print(c)
cities.pop(l-1)

File Handling
Q1. Write a function Push() which takes number as argument and add in a stack "MyValue"

Answer:
MyValue=[]
def Push(value):
MyValue.append(value)

Q2. Write a function Push that takes "name" as argument and add in a stack named "MyStack"

Answer:
Mynames=[]
def Push(Value):
Mynames.append(Value)
Push("Amit")

Q3. Write a function Push() which takes "name" as argument and add in a stack named
"MyStack". After calling push() three times, a message should be displayed "Stack is
Full"

Answer:
MyStack=[]
StackSize=3
def Push(Value):
if len(MyStack) < StackSize:
MyStack.append(Value)
else:
print("Stack is full!")

Q4. Write a function pop() which remove name from stack named "MyStack".

Answer:
def Pop(MyStack):
if len(MyStack) > 0:
MyStack.pop()
else:
print("Stack is empty.")

Q5. Write push(rollno) and pop() method in python:


push(rollno) --add roll number in Stack
pop() --- remove roll number from Stack.

Answer:
MyStack=[]
def Push(rollno):
MyStack.append(rollno)
def Pop(MyStack):
if len(MyStack) > 0:
MyStack.pop()
else:
print("Stack is empty.")

Q6. Write add(bookname) and delete() method in python to add bookname and remove
bookname considering them to act as push() and pop() operations in stack.

Answer:
MyStack=[]
def add(bname):
MyStack.append(bname)
def delete(MyStack):
if len(MyStack) > 0:
MyStack.pop()
else:
print("Stack is empty. There is no book name")

Q7. Write addclient(clientname) and remove() methods in python to add new client and
delete existing client from a list "clientdetail", considering them to act as push and pop
operations of the stack.

Answer:
clientdetail=[]
def addclient(cn):
clientdetail.append(cn)
def remove():
if len(clientdetail)>0:
clientdetail.pop()
else:
print("Stack is empty")

Q8. Write a function in Python that counts the number of “Me” or “My” (in smaller case also) words
present in a text file “STORY.TXT”. If the “STORY.TXT” contents are as follows:

My first book was Me and My Family. It gave me chance to be Known to the world.

The output of the function should be: Count of Me/My in file: 4

Answer:
Q9. Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurence of alphabets ‘A’ and ‘M’ (including small
cases ‘a’ and ‘m ‘too). Example: If the file content is as follows:

Updated information As simplified by official websites.

The AMCount() function should display the output as: A or a = 4, M or m =2

Answer:

Q10. Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which is
starting with an alphabet ‘A’ .

Answer:

Q11. Write a method/function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT, and display those words, which are less than 4 characters.
Answer:

Q12. Write a function RevText() to read a text file “ Story.txt “ and Print only word starting with ‘I’ in
reverse order . Example: If value in text file is: INDIA IS MY COUNTRY Output will be: AIDNI SI
MY COUNTRY.

Answer:

Q13. Write a function in python to count the number of lowercase alphabets present in a text file
“Story.txt”

Answer:
Q14. Write a user-defined function named count() that will read the contents of text file named
“Story.txt” and count the number of lines which starts with either “I‟ or “M‟. E.g. In the following
paragraph, there are 2 lines starting with “I‟ or “M‟:

“India is the fastest growing economy.


India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.”

Answer:

Q15. Write a user defined function countwords() in python to count how many words are present in
a text file named “story.txt”. For example, if the file story.txt contains following text:

Co-education system is necessary for a balanced society. With co-education system, Girls and
Boys may develop a feeling of mutual respect towards each other.

The function should display the following:

Total number of words present in the text file are: 24

Answer:
Q16. Write a user defined function in Python that displays the number of lines starting with ‘H’ in
the file story.txt. Eg: if the file contains:

Whose woods these are I think I know.


His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.

Then the line count should be 2

Answer:

Binary File:

Q1. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE].
(i) Write a user defined function MakeFile( ) to input data for a record and add to
Book.dat.
(ii) Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as parameter and
return PRICE of the Item stored in Binary file STOCK.DAT.

Answer:

(i)
import pickle
def MakeFile():
fobj=open("STOCK.DAT",'ab')
itemid=input("Enter ITEM ID")
itemname=input("Enter name of the Item")
Q=int(input("Enter the quantity of Item"))
price=float(input("Enter the price"))
rec=[itemid,itemname,Q,price]
pickle.dump(rec,fobj)
fobj.close()

(ii)
def GetPrice(ITEMID):
fobj=open("STOCK.DAT",'rb')
try:
while True:
rec=pickle.load(fobj)
if(rec[0]in str(ITEMID)):
print("Price of ", rec[0], "item is",rec[3])
return rec[0]
except:
fobj.close()
Q2. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a
function CountRec( ) in Python that would read contents of the file “EMPLOYEE.DAT” and display
the details of those Employees whose Salary is above 20000. Also display number of employees
having Salary more than 20000.

Answer:
import pickle
def CountRec():
fobj=open("EMPLOYEE",'rb')
num=0
try:
while True:
rec=pickle.load(fobj)
if(rec[2]>20000):
print(rec[0],rec[1],rec[2])
num=num+1
except:
fobj.close()
return num

Q3. A binary file “Computers.dat” has structure [CNo, Make, Model, Price].
The description is given below:
CNo : Computer Number e.g. 278548
Make : Make of PC e.g. HP
Model : Model Number e.g. VXPC126
Price : Price of computer e.g.40258.99

i. Write a user defined function CreatePC() to input data for a record and append into
Computers.dat .
ii. Write a function FindPCs(Price) in Python which accepts the Price as parameter and display
only those computer records from Computers.dat which are having less than or equal to given
price.

Answer:

import pickle
(i)def CreatePC():
lst=[2726,"Accer","SHWH",49500.25] #list
f=open("d:\\Computers.dat","ab+") # file in binary mode
pickle.dump(lst,f) # adding in binary file
f.close()

(ii)
def FindPCs(prc):
f=open("d:\\Computers.dat","rb") # Open in read mode
while True:
try:
rec=pickle.load(f) # Reading from file till end
if prc>=rec[3]:
print("-----------------------------------")
print("CNo:",rec[0])
print("Make:",rec[1])
print("Model:",rec[2])
print("Price:",rec[3])
except EOFError:
break
print("-----------------------------------")
f.close()

Q4. A binary file “CLUB.DAT” has structure (PNO, PName, Game,Fee).


The description is given below:
PNo : Player Number e.g. 365478
PName : Player Name e.g. “Rajat”
Game : Game of Player e.g. “Basketball”
Fee : Coaching Fee e.g.12500.00

Write a function Player_Count() in Python that would read contents of the file “CLUB.DAT” and
display the details of those players whose fee is above 7500. Also display number of players
paying fee above 10000.

Answer:

def Player_Count():
f=open("d:\\Club.dat","rb") # Open in read mode
count=0
while True:
try:
rec=pickle.load(f) # Reading from file till end
if 7500>=rec[3]:
print("-----------------------------------")
print("PNo:",rec[0])
print("Name:",rec[1])
print("Game:",rec[2])
print("Fee:",rec[3])
if rec[3]>10000:
count=count+1
except EOFError:
break
print("-----------------------------------")
print("No of player paying fee above 10000=",count)
f.close()

Q5. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].

Write a user defined function CreateFile() to input data for a record and add to Book.dat .
Write a function CountRec(Author) in Python which accepts the Author name as parameter and
count and return number of books by the given Author are stored in the binary file “Book.dat

Answer:
import pickle
def createfile():
fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()

createfile() # This function is called just to verify result and not required in exam

def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
fobj.close()
return num

n=countrec("amit") # This function is called just to verify result and not required in exam
print("Total records", n) # This statement is just to verify result and not required in exam

Q6. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a
function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the
details of those students whose percentage is above 75. Also display number of students scoring
above 75%.

Answer:

import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num

Q7. Write a function in python to search and display details, whose destination is “Cochin” from
binary file “Bus.Dat”. Assuming the binary file is containing the following elements in the list:

Bus Number
Bus Starting Point
Bus Destination

Answer:

import pickle
def countrec():
fobj=open("bus.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() # This function is called just to verify result
print(n)

Q8. Write a function addrec() in Python to add more new records at the bottom of a binary file
“STUDENT.dat”, assuming the binary file is containing the following structure :

[Roll Number, Student Name]

Answer:
import pickle
def addrec():
fobj=open("student.dat","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
pickle.dump(rec,fobj)
fobj.close()
addrec()

Q9. Write a function searchprod( pc) in python to display the record of a particular product from a
file product.dat whose code is passed as an argument. Structure of product contains the following
elements [product code , product price]

Answer:
import pickle
def searchprod(pc):
fobj=open("product.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[0]==pc:
print(rec)
except:
fobj.close()

n=searchprod(1) # This function is called to verify the result

Q10. Write a function routechange(route number) which takes the Route number as parameter
and modify the route name(Accept it from the user) of passed route number in a binary file
“route.dat”.

Answer:

import pickle
def routechange(rno):
fobj=open("route.dat","rb")
try:
while True:
rec=pickle.load(fobj)
if rec[0]==rno:
rn=input("Enter route name to be changed ")
rec[1]=rn
print(rec) #This statement is called to verify the change in the record
except:
fobj.close()

routechange(1) # This function is called to verify the result

Q11. Write a function countrec(sport name) in Python which accepts the name of sport as
parameter and count and display the coach name of a sport which is passed as argument from the
binary file “sport.dat”. Structure of record in a file is given below ——————– – [sport name,
coach name]

Answer:

def countrec(sn):
num=0
fobj=open("data.dat","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=pickle.load(fobj)
if rec[0]==sn:

print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:
fobj.close()

Q12. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a
function countrec() in Python that would read contents of the file “salary.DAT” and display the
details of those employee whose salary is above 20000.

Answer:
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

Q13. Amit is a monitor of class XII-A and he stored the record of all the students of his class in a
file named “class.dat”. Structure of record is [roll number, name, percentage]. His computer
teacher has assigned the following duty to Amit
Write a function remcount( ) to count the number of students who need remedial class (student
who scored less than 40 percent)

Answer:

def countrec():
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

Q14. A binary file “emp.dat” has structure [employee id, employee name]. Write a function
delrec(employee number) in Python that would read contents of the file “emp.dat” and delete the
details of those employee whose employee number is passed as argument.

Answer:
Q15. Write a function addrecord() to add record of teacher in file “teacher.dat” Each record should
contain the following data (using list) :

Teacher Name
Teacher designation
Teacher Salary

Answer:

Q16. Write a function displayrec() to read and display the record of a particular teacher according
to the name entered by the user from a file “teacher.dat” (created above)

Answer:
CSV File
Q1. Write a program to read entire data from file data.csv

Answer:

import csv
f=open("data.csv", 'r')
d=csv.reader(f)
for row in d:
print(row)

OUTPUT:

['Admno', 'Name', 'Class', 'Sec', 'Marks']


['1231', 'Amit', 'XII', 'A', '45']
['1224', 'Anil', 'XII', 'B', '49']
['1765', 'Suman', 'XI', 'A', '42']
['2132', 'Naman', 'XII', 'C', '38']

OR

We can also write the program in the following way

import csv
with open("data.csv",'r') as f:
d=csv.reader(f)
for row in d:
print(row)

Q2. Write a program to search the record from “data.csv” according to the admission number input
from the user. Structure of record saved in “data.csv” is Adm_no, Name, Class, Section, Marks

Answer:

import csv
f = open("data.csv",'r')
d=csv.reader(f)
next(f) #To Skip Header Row
k=0
adm = int(input("Enter admission number"))
for row in d:
if int(row[0])==adm:
print("Adm no = ", row[0])
print("Name = ", row[1])
print("Class = ", row[2])
print("Section = ", row[3])
print("Marks = ", row[4])
break
else:
print("Record Not Found")

OUTPUT :
Enter admission number1231
Adm no = 1231
Name = Amit
Class = XII
Section = A
Marks = 45

Q3. Write a program to add/insert records in file “data.csv”. Structure of a record is roll number,
name and class.

Answer:

import csv
field = ["Roll no" , "Name" , "Class"]
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)
ch='y'
while ch=='y' or ch=='Y':
rn=int(input("Enter Roll number: "))
nm = input("Enter name: ")
cls = input("Enter Class: ")
rec=[rn,nm,cls]
d.writerow(rec)
ch=input("Enter more record??(Y/N)")
f.close()

Q4. Write a program to copy the data from “data.csv” to “temp.csv”

Answer:
import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )

Q5. Write a program to read all content of “student.csv” and display records of only those students
who scored more than 80 marks. Records stored in students is in format : Rollno, Name, Marks

Answer:
import csv
f=open("student.csv","r")
d=csv.reader(f)
next(f)
print("Students Scored More than 80")
print()
for i in d:
if int(i[2])>80:
print("Roll Number =", i[0])
print("Name =", i[1])
print("Marks =", i[2])
print("--------------------")
f.close( )

OUTPUT
Students Scored More than 80

Roll Number = 1
Name = Amit
Marks = 81
--------------------------
Roll Number = 2
Name = Suman
Marks = 85
-------------------------
Roll Number = 4
Name = Deepika
Marks = 89
-------------------------

Q6. Write a program to display all the records from product.csv whose price is more than 300.
Format of record stored in product.csv is product id, product name, price,.

Answer:

import csv
f=open("product.csv" , "r")
d=csv.reader(f)
next(f)
print("product whose price more than 300")
print()
for i in d:
if int(i[2])>300:
print("Product id =", i[0])
print("Product Name =", i[1])
print("Product Price =", i[2])
print("--------------------")
f.close( )

OUTPUT:
product whose price more than 300

Product id =2
Product Name = Mouse
Product Price = 850
---------------------------------
Product id =3
Product Name = RAM
Product Price = 1560
--------------------------------
Q7. Write a program to calculate the sum of all the marks given in the file “marks.csv. Records in
“marks.csv” are as follows :
Rollno, Name, Marks
1, Suman, 67
2, Aman,71
3, Mini, 68
4, Amit, 80

Answer:

import csv
f=open("marks.csv","r")
d=csv.reader(f)
next(f)
s=0
for i in d:
s=s + int(i[2])
print("Total Marks are " ,s)
f.close( )

Q8. Write a program to count number of records present in “data.csv” file.

Answer:

import csv
f = open("data.csv" , "r")
d = csv.reader(f)
next(f) #to skip header row
r=0
for row in d:
r = r+1
print("Number of records are " , r)

Q9. Write a program to modify the record of a student in a file “data.csv”. Following records are
saved in file.
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, suman, 25

Answer:

import csv
import os
f=open("data.csv","r")
f1 = open("temp.csv","w")
d=csv.reader(f)
d1=csv.writer(f1)
next(f)
s=0
rollno = int(input("Enter roll number :"))
mn=input("Enter modified name :")
mm = int(input("Enter modified marks :"))
mr=[rollno,mn,mm]
header =["Rollno", "Name", "Marks"]
d1.writerow(header)
for i in d:
if int(i[0])==rollno:
d1.writerow(mr)
else:
d1.writerow(i)
os.remove("data.csv")
os.rename("temp.csv","data.csv")
f.close()
f1.close()

Execution of Program
Enter roll number :4
Enter modified name :Sumati
Enter modified marks :45

After modification, data in the file will be

Rollno, Name, Marks


1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, sumati, 45

Q10. Write a program to show the detail of the student who scored the highest marks. Data stored
in “Data.csv” is given below :
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, suman, 25

Answer:
import csv
f=open("data.csv","r")
d=csv.reader(f)
next(f)
max=0
for i in d:

if int(i[2])>max:
max=int(i[2])
f.close()
f=open("data.csv","r")
d=csv.reader(f)
next(f)
for i in d:
if int(i[2])==max:
print(i)
f.close()

Execution of Program :

['1' , ' Aman' , ' 35']

List in Python

Q1. Write a function find(name) in python to display all the names from a list of names which are
starting from alphabet ‘p’.
Answer:

name = ['Amit' , 'Sumit', 'Pooja' , 'Mini' , 'Ronit' , 'Abdul', 'Poonam']

def find(name):
for i in name:
if i[0]=='p' or i[0]=='P':
print(i)

find(name)

OUTPUT:
Pooja
Poonam

Q2. Write a function disp(name) in python to display all the names from a list of names whose
length is of four characters.
Answer:
name = ['Amit' , 'Sumit', 'Pooja' , 'Mini' , 'Ronit' , 'Abdul', 'Poonam']
def disp(name):
for i in name:
if len(i)==4:
print(i)

disp(name)

OUTPUT:
Amit
Mini

Q3. Write a function previous(List, name) which is accepting list of names and a name and display
the index value of the first occurence of the name passed in the list.
Ans.

name = ['Amit' , 'Sumit', 'Pooja','Mini' , 'Ronit' , 'Abdul', 'Poonam']

def previous(L,n):
c=-1
for i in L:
c=c+1
if i.lower()==n.lower():
print("Index Value is ",c)
break
else:
print("Name not found")
previous(name, 'sumit')

OUTPUT :
Index Value is 1

Q4. Write a program in python which multiply all the numbers in the list by 3.
L = [‘Amit’ , ‘Suman’, 4, 8, ‘Jack’, 9]

Answer:

L = ['Amit' , 'Suman', 4, 8, 'Jack', 9]

c=0

for i in L:

if str(i).isdigit():

L[c]=L[c]*3

c=c+1

print(L)

OUTPUT:
['Amit', 'Suman', 12, 24, 'Jack', 27]

Q5. Write a program in python which add all the numbers in the list.
L = [‘Keyboard’, 7, ‘Ram’ , 9, ‘Monitor’ , 11 , ‘Mouse’]

Answer:
L = ['Keyboard', 7, 'Ram' , 9, 'Monitor' , 11 , 'Mouse']

s=0

for i in L:

if str(i).isdigit():

s=s+i

print(s)

OUTPUT:
27

Q6. Write a program in python which convert all the odd numbers in the list to even by adding 1.
Answer:

L = [13,21,32,24,55,26,17,38,59]
for i in range(len(L)):

if L[i] % 2 != 0:

L[i] = L[i]+1

print(L)

OUTPUT :
[14, 22, 32, 24, 56, 26, 18, 38, 60]

Q7. Write a program in python which print the table of first even number. like the list is L = [23, 13,
101, 6, 81, 9, 4] so table of 6 will be printed.
Answer:

L = [23, 13, 101, 6, 81, 9, 4]


for i in range(len(L)):
if L[i]%2==0:
for j in range(1,11):
print(L[i] * j)
break
L[i]=L[i]+1

Q8. Write a program in python which swap the alternate members of list (assuming that even
number of elements in the list). like as shown below:
Original List : L = [23, 45, 67, 29, 12, 1]

After Swaping : L = [45,23, 29, 69, 1, 12]

Answer:
L = [23, 13, 101, 6, 81, 9, 4, 1]

for i in range(0, len(L), 2):

L[i], L[i+1] = L[i+1], L[i]

print(L)

OUTPUT:
[13, 23, 6, 101, 9, 81, 1, 4]

Q9. Write a function mul7(list) in python which takes list as argument and multiply only those
numbers which are multiples of 7.
Answer:

def mul7(L):

r=1

for i in L:

if i %7 == 0:
r = r*i

print(r)

L = [34, 23, 21, 49, 7, 8]

mul7(L)

OUTPUT:
7203

Q10. Write a program in python which concatenate all the numbers present in the list.
Original List : [12, 34, 43, 2, 34]

Output = 123443234

Answer:

L = [34, 23, 21, 49, 7, 8]

r = ""

for i in L:

r = r + str(i)

print(r)

OUTPUT:
3423214978

Q11. Write a program in python which display only those names from the list which have ‘i’ as
second last character. like L = [“Amit”, “Suman”, “Sumit”, “Montu” , “Anil”]
Output :

Amit

Sumit

Answer:

L = ["Amit" , "Suman" , "Sumit" , "Montu" , "Anil"]


for i in L:
if i[-2]=='i':
print(i)

OUTPUT :
Amit
Sumit
Anil

Q12. Write a program in python which display only those names from the list Whose first character
is vowel. like L = [“Amit”, “Suman”, “Sumit”, “Montu” , “Uma”, “Emil”]
OUTPUT is :
Amit

Uma

Emil

Answer:

L = ["Amit" , "Suman" , "Sumit" , "Montu" , "Uma" , "Emil"]

vow="aeiouAEIOU"

for i in L:

if i[0] in vow:

print(i)

OUTPUT :

Amit
Uma
Emil
Q13. Write a program in python which removes the last element from the list and insert it in the
beginning. like
Original List : L = [1, 3, 2, 34, ‘amit’, 7, 5]

News List : L = [5, 1, 3, 2, 34, ‘amit’, 7]

Answer:
L = [1, 3, 2, 34, 'amit', 7, 5]

L.insert(0, L.pop())

print(L)

Q14. Write a function countf(List, num) which takes a list of numbers and a number as an
argument and display the frequency of that number in the list.(without using inbuilt function ‘count’)
Answer:

L = [1, 3, 2, 34, 3, 7, 5]

def countf(L, n):

c=0

for i in L:

if i==n:

c=c+1

print("frequency of" , n , "is" , c)


countf(L,3)

Q15. Write a function change(L, n) which takes a list and number as an argument and remove that
much elements from the end of the list and add those numbers in the beginning of the list. for
example
Original List : L = [34, 23, 12, 54, 43, 89, 67]

Output List : L = [43, 89, 67, 34, 23, 12, 54 ] # if the number passed is 3

Original List : L = [34, 23, 12, 54, 43, 89, 67]

Output List : L = [54, 43, 89, 67, 34, 23, 12] # if the number passed is 4

Answer:

L = [34, 23, 12, 54, 43, 89, 67]

def change(L, n):

for i in range(n, 0, -1):

L.insert(0, L.pop())

print(L)

change(L, 4)

OUTPUT :
[54, 43, 89, 67, 34, 23, 12]

Q16. Write a function double(L) in python which take a list as an argument and if an element is
numeric then multiply it by 3 and if it is a string then concatenate that element with itself. for
example
Original List : L = [1, 2, ‘amit’, 5, ‘list’]

Output List : L = [3, 6, ‘amitamit’ , 15 , ‘listlist’]

Answer:

L = [1, 2, 'amit', 5, 'list']

def double(L):

for i in range(len(L)):

if str(L[i]).isdigit():

L[i]=L[i]*3

else:

L[i]=L[i]*2

print(L)
double(L)

OUTPUT :
[3, 6, 'amitamit' , 15 , 'listlist']

Q17. Write a program that arrange all odd numbers on left side of the list and even numbers on
the right side of the list. for example
Original List : L = [23, 44, 65, 78, 34, 21, 9]

Output List : L = [9, 21, 65, 23, 44, 78, 34]

Answer:

L = [23, 44, 65, 78, 34, 21, 9]

for i in L:

c=0

k=0

if i%2!=0:

k=L.index(i)

L.insert(c, L.pop(k))

c=c+1

else:

c=c+1

print(L)

OUTPUT:
[9, 21, 65, 23, 44, 78, 34]

Q18. Write a function disp(L) which takes a given list of five names as argument and display only
those names which are starting from either ‘A’ or ‘E’. L = [“Amit”, “Esha”, “Sumit”, “Naman”, “Anuj”]
Answer:

L = ["Amit", "Esha","Sumit", "Naman", "Anuj"]

def disp(L1):

for i in L1:

if i[0] in' AaEe':

print(i)

disp(L)
OUTPUT :

Amit
Esha
Anuj

Dictionary in Python
Q1. Write a program to store information of products like product id, product name, and product
price in a dictionary by taking product id as a key.

Answer:
t=int(input(“Enter number of terms”))

prod={ }

for i in range(t):

pid=int(input(“Enter product id”))

pn=input(“Enter product name”)

pp=int(input(“Enter product price”))

temp=(pn, pp)

prod[pid]=temp

print(prod)

Q2. Write a program to accept the employee id from the user and display its detail from the
dictionary. Data is stored in the dictionary in the following format
{Empid : (Empname, EmpSalary}

Answer:

emp={1:(“Amit”,25000),2:(“Suman”,30000),3:(“Ravi”,36000)}

pid=int(input(“Enter the product id”))

l=[ ]

if pid in emp:

l=emp[pid]

print(“Employee id, Employee Name”, “\t””Salary”)

print(pid,”\t””\t””\t””\t”,l[0],”\t””\t”,l[1])

else:

print(“Record not found”)


Q3. Write a program to accept the employee id from the user and check Salary. If salary is less
than 25000 then increase the salary by Rs1000. Data is stored in the dictionary in the following
format
{Empid : (Empname, EmpSalary}

Answer:
emp={1:(“Amit”,25000),2:(“Suman”,30000),3:(“Ravi”,36000)}

pid=int(input(“Enter the product id”))

l=[ ]

if pid in emp:

l=emp[pid]

if l[1]>25000:

emp[pid]=(l[0],l[1]+500)

print(emp)

Q4. Write a program to display the name of all the employees whose salary is more than 25000
from the following dictionary.
emp={1:(“Amit”,25000),2:(“Suman”,30000),3:(“Ravi”,36000)}
Format of data is given below :
{Empid : (Empname, EmpSalary}

Answer:
emp={1:(“Amit”,25000),2:(“Suman”,30000),3:(“Ravi”,36000)}

d=list(emp.values())

print(“Employees whose Salary more than 25000 are”)

for i in d:

if i[1]>25000:

print(i[0])

Q5. Write a program to count the frequency of each word in a given string accepted from the user
using dictionary.

Answer:
str1=input(“Enter any String”)

w=str1.split()

d={ }

for i in w:
if i not in d:

d[i]=w.count(i)

for i in d:

print(“frequency of “, i , ” is ” , d[i])

Q6. Write a program to accept roll number, names and marks of five students and store the detail
in dictionary using roll number as key. Also display the sum of marks of all the five students.

Answer:

d={ }

s=0

for i in range(5):

rn = int(input(“Enter roll number”))

nm = input(“Enter name “)

mrk = input(“Enter marks”)

temp=(nm, mrk)

d[rn]=temp

for i in d:

L=d[i]

s=s+int(L[1])

print(“Sum of marks “, s)

Q7. Write a program to count the frequency of each character in a given string accepted from the
user using dictionary.(Store the character as key and it’s frequency as value)

Answer:

str1=input(“Enter any String”)

d={ }

for i in str1:

if i not in d:

d[i]=str1.count(i)

for i in d:
print(“frequency of “, i , ” is ” , d[i])

String in Python

Q1. Write a program to accept a string and count number of vowels.

Answer:
str = input("Enter any String")
s1="aeiouAEIOU"
v=0
for i in str:
if i in s1:
v=v+1
print(v)

Q2. Write a program to accept a string and display it in reverse.

Answer:

str = input("Enter any String")


print(str[: :-1])

Q3. Write a program to check whether an input string is palindrome or not.

Answer:
str = input("Enter any String")
strrev =""
for i in range(len(str),0,-1):
strrev=strrev + str[i-1]
if str.lower() == strrev.lower():
print("Palindrome")
else:
print("Not a palindrome")

Q4. Write a program to count number of small case alphabets in String.

Answer:

str = input("Enter any String")


L=0
for i in str:
if i.islower( ):
L = L+1
print("Total small case alphabets are : ",l)
String Datatype
String Datatype
Q5. Write a program to count the number of words in the input string.

Answer:

str = input("Enter any String")


L=str.split()
print("Total number of words are ", len(L))

Q6. Write a program to accept a string from the user and count the frequency of alphabet ‘a’ and
‘c’.

Answer:

str = input("Enter any String")


a=0
c=0
for i in str:
if i=='a':
a+=1
if i=='c':
c+=1
print("Total number of alphabet 'a' is ", a)
print("Total number of alphabet 'c' is ", c)

Q7. Write a program to display the last word of the string accepted from user.

Answer:

str = input("Enter any String")


w=str.split()
print(w[-1])

Q8. Write a program to display those words from the string in python which are starting from
alphabet ‘a’ or ‘A”.

Answer:
str = input("Enter any String")
w=str.split()
c=0
for i in w:
if i[0]=='a' or i[0]=='A':
c=c+1
print("Total words starting from 'a' or 'A' : ",c)

Q9. Write a program to count number of digits in a string accepted from user.

Answer:
str = input("Enter any String")
d=0
for i in str:
if i.isdigit():
d=d+1
print("Total digits are : ",d)

Q10. Accept a string from the user and display the string with first character of each word Capital.
(Without using inbuilt function)
Answer:

str = input("Enter any String")

str1 = ""

L=str.split()

for i in L:

str1 = str1 + i[0].upper() + i[1:] +" "

print(str1)

Q11. Write a program to accept a string from the user and display n characters from the left of the
string. (Accept n from the user)
Answer:

str = input("Enter any string")

n=int(input("Enter number of characters to be extract from left"))

L = len(str)

if n > L :

print("Enter less number of characters")

else:

print(str[ : n ])

Q12. Write a program to reverse the string using slicing.


Answer:
str = "String Slicing in Python"
print(str[: : -1])

OUTPUT is:

nohtyP ni gnicilS gnirtS

Q13. Write a program to accept a string from the user and display n characters from the right of
the string. (Accept n from the user)
Answer:

str = "String Slicing in Python"


n = int(input("Enter number of characters"))
l = len(str)
print(str[l-n : : ])

Q14. Accept a String from the user and display first two characters of each word in same line
separated by space.
Answer:

str = "String Slicing in Python"


word = str.split()
for i in word:
print(i[0 : 2], end = " ")

OUTPUT :
St Sl in Py

Q15. Write a program to display the largest word from the string.
Answer:

str=input("Enter any String :")


L = str.split()
max=0
b=""
for i in L:
if len(i) > max:
b=i
max=len(i)
print("Longest word is ",b)

Q16. Write a program to accept a string and display it in upper case.


Answer:
str=input("Enter any String :")
print(str.upper( ))

#Execution of program is :

Enter any String :String Programs


STRING PROGRAMS

Q17. Write a program to display the unique words from the string.
Answer:

str=input("Enter any String :")


L=str.split( )
L1=[ ]
for i in L:
if i not in L1:
L1.append(i)
str=""
for i in L1:
str=str+" "+i
print("String with unique words are :",str)

Execution of Program
Enter any String : string program practice string program
String with unique words are : string program practice

Q18. Write a program to accept a string and display the ascii value of each character.
Answer:

str=input("Enter any String :")


for i in str:
print("ASCII value of ",i,"is",ord(i))

#Execution of the program


Enter any String : String Programs
ASCII value of S is 83
ASCII value of t is 116
ASCII value of r is 114
ASCII value of i is 105
ASCII value of n is 110
ASCII value of g is 103
ASCII value of is 32
ASCII value of P is 80
ASCII value of r is 114
ASCII value of o is 111
ASCII value of g is 103
ASCII value of r is 114
ASCII value of a is 97
ASCII value of m is 109
ASCII value of s is 115

Q19. Write a program to accept a string and replace all spaces by ‘#’ symbol.
Answer:
.

str=input("Enter any String :")


str1=""
for i in str:
if i.isspace():
str1=str1+'#'
else:
str1=str1+i
print("Output String is :",str1)

#Execution of program

Enter any String :practice string programs


Output String is : practice#string#programs

Q20. Write a program to accept two strings from the user and display the common words.(Ignore
case)
Answer:
str1=input("Enter first String :")
str2=input("Enter second String :")
L1=str1.split()
L2=str2.split()
for i in L1:
if i in L2:
print(i)

#Execution of program is :

Enter first String : program string programs


Enter second String : program
Program

Q21. Write a program to accept a string and count the frequency of each vowel.
Answer:
str1=input("Enter String :")
print("frequency of vowel 'a' is :",str1.count('a'))
print("frequency of vowel 'e' is :",str1.count('e'))
print("frequency of vowel 'i' is :",str1.count('i'))
print("frequency of vowel 'o' is :",str1.count('o'))
print("frequency of vowel 'u' is :",str1.count('u'))

#Execution of program

Enter String :Important String Programs


frequency of vowel 'a' is : 2
frequency of vowel 'e' is : 0
frequency of vowel 'i' is : 1
frequency of vowel 'o' is : 2
frequency of vowel 'u' is : 0

Q22. Write a program to display the smallest word from the string.
Answer:
str=input("Enter any String :")
L = str.split()
min=50 #we think that length of any word in the string is not larger than 50 (can give any other
number)
b=""
for i in L:
if len(i) < min:
b=i
min=len(i)
print("Smallest word is : ",b)

#Execution of program:

Enter any String :important string programs


Smallest word is : string

Q23. Write a program to accept a string and display the string in Title case. (first alphabet of each
word in upper case)
Answer:
str=input("Enter any String :")
print(str.title())
#Execution of program is :

Enter any String :my name is amit


My Name Is Amit
Q24. Write a program to accept a string and display the string with changed case.(Change upper
case alphabet to lower case and vice versa)
Answer:

str=input("Enter any String :")


print(str.swapcase())

#Execution of program is :
Enter any String :My name is Amit
mY NAME IS aMIT

Q25. Write a program to accept a string and display the string with second alphabet of each word
in upper case.
Answer:

str = input("Enter any String")

str1 = ""

L=str.split( )

for i in L:

str1 = str1 + i[0] + i[1].upper() + i[2:] +" "

print(str1)
Q26. Write a program to accept a string and display the word which has vowel ‘a’ in it.
Answer:
.

str = input("Enter any String")

L=str.split()

for i in L:

if 'a' in i:

print(i)
Q27. Write a program to accept the first name from the user and display it as much times as its
length.
Answer:
str = input("Enter first name")

for i in range(len(str)):
print(str)

Q28. Write a program to accept any string from the user and display it in the following pattern
if the string entered is “Python String Programs” then the output should be
Python
Python String
Python String Programs
Answer:

str = input("Enter any string")

L=str.split()

str1 = ""

for i in L:

str1 = str1 + i

print(str1)

Q29. Write a program to accept a string from the user and display the string without space.
Answer:

str = input("Enter any string")

str1=""

for i in str:

if i.isspace()==False:

str1=str1+i

print(str1)

Q30. Write a program to accept a string and substring from the user and display the frequency of
substring in string.
Answer:

str = input("Enter any string")


substr=input("Enter any substring")
print(str.count(substr))

Q31. Write a program to replace all ‘a’ in a string by symbol ‘@’.


Hide Answer
Ans.

str = input("Enter any string")

str1=""

for i in str:

if i!='a':

str1=str1+i

else:
str1=str1+'@'

print(str1)

Q32. Write a program to accept a string and substring from the user and check whether the
substring is existing/present in string or not.
Answer:

str = input("Enter any string")

substr=input("Enter any substring")

if (str.find(substr)!=-1):

print("Substring is present")

else:

print("Substring is not present")

Q33. Write a program to accept a string from the user and display n characters from the right of
the string. (Accept n from the user)
Answer:

str = input("Enter any string")

n=int(input("Enter number of characters to be extract from right"))

L = len(str)

if n > L:

print("Enter less number of characters")

else:

print(str[-n:])

Q34. Write a program to accept a word from the user and display it in the following pattern.
if the word is “river” then it should display as shown below
r
ri
riv
rive
river
Answer:

str = input("Enter any string")

str1 = ""

for i in str:

str1 = str1 + i
print(str1)

Pattern Programs in Python


Write a program in Python to print the following pattern
Q1.

12

123

1234

12345

Answer:
for i in range(1, 6):
for j in range(1, i+1):
print(j, end = " ")
print()

Q2.

54321

5432

543

54

Answer:

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

Q3.

55555

4444

333
22

Answer:

for i in range(5, 0, -1):


for j in range(i):
print(i, end = " ")
print()

Q4.

12345

1234

123

12

Answer:

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

Q5.

22

333

4444

55555

Answer:

for i in range(1, 6):


for j in range(1, i+1):
print(i, end = " ")
print()

Q6.

5
44
333
2222
11111

Answer:

for i in range(5, 0,-1):


for j in range(6,i,-1):
print(i, end = " ")
print()

Q7.

5
54
543
5432
54321

Answer:

for i in range(5, 0,-1):


for j in range(5,i-1,-1):
print(j, end = " ")
print()

Q8.

1
12
123
12 3 4
123 4 5
Answer:
for i in range(5):
for j in range(5-i-1):
print(" ",end=" ")
for j in range(i+1):
print(j+1, end=" ")
print()

Q9.

1
22
333
44 4 4
555 5 5

Answer:
for i in range(5):
for j in range(5-i-1):
print(" ",end=" ")
for j in range(i+1):
print(i+1, end=" ")
print()

Q10.

1
21
321
43 2 1
543 2 1
Answer:

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

Q11.

21

321

4321

54321

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

Q12.

23

456

7 8 9 10

Answer:
(This triangle is called Floy'd triangle)

c=1
st = 2
for i in range(3):
for j in range(1, st):
print(c, end=" ")
c += 1
print()
st = st+1

Q13.

234

56789

Answer:

c=1
st = 2
for i in range(3):
for j in range(1, st):
print(c, end=" ")
c += 1
print()
st = st+2

Q14.

01

024

0369

0 4 8 12 16

Answer:

for i in range(0, 5):


for j in range(0, i+1):
print(j*i, end = " ")
print()

Q15.

0
01
014
0149
0 1 4 9 16
Answer:
.

for i in range(0, 5):


for j in range(0, i+1):
print(j*j, end = " ")
print()

Q16.

1
44
999
16 16 16 16
25 25 25 25 25

Answer:

for i in range(1,6):
for j in range(1,i+1):
print(i*i, end = " ") #print(i**2, end = " ") can also be written
print()

Q17.

1
33
555
7777
99999

Answer:

for i in range(1,6):
for j in range(1,i+1):
print(i*2-1, end = " ")
print()

Q18.

*
* *
* * *
* * * *
* * * * *
Answer:

for i in range(1,6):
for j in range(i):
print(" * ", end = "")
print( )

Q19.
* * * * *
* * * *
* * *
* *
*
Answer:

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

Q20.

*
**
***
****
*****

Answer:
n=5
sp = 2 * n - 2
for i in range(0, n):
for j in range(0, sp):
print(end=" ")
sp = sp - 2
for j in range(0, i + 1):
print("* ", end = "")
print()

Q21.

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Answer:

for i in range(6):
for j in range(1,6):
print(j, end = " ")
print()

Q22.

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

Answer:

for i in range(1,6):
for j in range(1,6):
print(i, end = " ")
print()

Q23.

A
A B
A B B
A B C D
A B C D E

Answer:

str = "A B C D E"


for i in range(1, 6):
print(str[ : i*2])

Q24.

A
B B
C C C
D D D D
E E E E E
Answer:
str = "ABCDE"
for i in range(5):
print(str[i]*(i+1))

Q25.

*
***
*****
*******

Answer:

num = 5
for i in range (1, num + 1):
sp = (num - i) * " "
print(sp, end = " ")
for k in range(i, 1, -1):
print("*", end = " ")
for j in range(1, i + 1):
print("*", end = " ")
print()

Q26.

Answer:
i)

n=3
for i in range (1, n + 1):
sp = (n - i) * " "
sym = (2 * i - 1) * "*"
print(sp, sym)
for j in range(n - 1, 0, -1):
sp = (n - j) * " "
sym = (2 * j - 1)* "*"
print(sp, sym)

ii)

num = 5
for i in range (1, num + 1):
sp = (num - i) * " "
print(sp, end = " ")
for k in range(i, 1, -1):
print(k, end = " ")
for j in range(1, i + 1):
print(j, end = " ")
print()

iii)

str = "123456"
for i in (str):
print(" " * int(i) + str[0 : len(str) - int(i)])

OR

num = 5
for i in range (num, 0, -1):
sp = (num - i) * " "
print(sp, end=" ")
for k in range(1, i + 1):
print(k, end=" ")
print()

iv)

num = 3
k=0
for i in range (1, num + 1):
sp = (num - i)*" "
print(sp, end=' ')
while (k != (2 * i - 1)) :
if (k == 0 or k == 2 * i - 2) :
print("*", end= "")
else :
print(" ", end = "")
k=k+1
k=0
print( )
for j in range (num - 1, 0, -1):
sp = (num - j) * " "
print(sp, end=" ")
k = (2 * j - 1)
while (k > 0) :
if (k==1 or k == 2 * j - 1):
print("*",end="")
else:
print(" ",end="")
k=k-1
print( )

Q27.

p
py
pyt
pyth
pytho
python

Answer:

str = "python"
for i in range(len(str)+1):
for j in range(i):
print(str[j], end = " ")
print()

Q28.

1
222
33333
4444444
555555555
Answer:

num = 5
for i in range (1, num + 1):
sp = (num - i) * " "
print(sp, end = " ")
for k in range(i, 1, -1):
print(i, end = " ")
for j in range(1, i + 1):
print(i, end = " ")
print()

Unit 2.
Computer Networks
Q1. Rehaana Medicos Center has set up its new center in Dubai. It has four buildings as shown in
the diagram given below:

Research
Accounts
Lab

Packaging
Store
Unit

Distance between various building are as follows:

Accounts to research Lab 55m

Accounts to store 150m

Store to packaging unit 160m

Packaging unit to research lab 60m


Accounts to packaging unit 125m

Store to research lab 180m

Number of Computers

Accounts 25

Research Lab 100

Store 15

Packaging Unit 60

As a network expert, provide the best possible answer for the following queries:

i) Suggest a cable layout of connections between the buildings.

ii) Suggest the most suitable place (i.e. buildings) to house the server of this organization.

iii) Suggest the placement of the following device with justification:

a) Repeater b) Hub/Switch

iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.

v) Which cable is best suited for above layout

Answer:
i) Layout-

Research
Accounts
Lab

Packaging
Store
Unit

ii)The most suitable place/ building to house the server of this organization would be building
Research Lab, as this building contains the maximum number of computers.

(iii)
a) For layout1, since the cabling distance between Accounts to Store is quite large, so a repeater
would ideally be needed along their path to avoid loss of signals during the course of data flow in
this route. For layout2, since the cabling distance between Store to Research Lab is quite large, so
a repeater would ideally be placed.

b) In both the layouts, a Hub/Switch each would be needed in all the buildings to interconnect the
group of cables from the different computers in each building.

(iv) Firewall

(v) Twisted Pair cable / Ethernet cable

Q2. Biyani Design and Training Institute is setting up its center in Jaipur with four specialized units
for Design, Media, HR and Training in separate buildings. The physical distances between these
units and the number of computers to be installed in these units are given as follows.
You as a network expert, have to answer the queries as raised by the administrator as given in (i)
to (v).
Shortest distances between various locations in meters :

Design Unit to Media Unit 60


Design Unit to HR Unit 40
Design Unit to Training Unit 60
Media Unit to Training Unit 100
Media Unit to HR Unit 50
Training Unit to HR Unit 60

Number of computers installed at various locations are as follows:

Design Unit 40
Media Unit 50
HR Unit 110
Training Unit 40

HR

DESIGN TRAINING

MEDIA
a) Suggest the most suitable place (i.e.,Unit/Building) to install the server of this Institute.
b) Suggest an ideal layout for connecting these Unit/Building for a wired connectivity.
c) Suggest the devices to be installed in each of these buildings for connecting computers installed
within each of the units out of the following :
Modem, Switch, Gateway, Router
d) Suggest an efficient as well as economic wired medium to be used within each unit for
connecting computer systems out of the following network cable :
Co-axial Cable, Ethernet Cable, Single Pair Telephone Cable.
e) The institute is planning to connect its admission office in Bangalore, which is 1960km from
institute. Which type of network out of LAN, MAN or WAN will be formed ? Justify your answer

Answer:

a. Most suitable place to install the server is HR Unit


b.

HR

DESIGN TRAINING

MEDIA

c. Switch
d. Ethernet Cable
e. WAN as the given distance is more than range of LAN and MAN.

Q3. Multipurpose Public School, Bengaluru is Setting up the network between its Different Wings
of school campus.
There are 4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).

Distance between various wings are given below:


Wing A to Wing S 100m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 300m
Wing S to Wing H 100m
Wing J to Wing H 450m

Number of Computers installed at various wings are as follows:


Wings Number of Computers
Wing A 20
Wing S 150
Wing J 50
Wing H 25

a. Suggest the best wired medium and draw the cable layout to efficiently connect various
wings of Multipurpose Public School, Bengaluru.
b. Name the most suitable wing where the Server should be
installed. Justify your answer.
c. Suggest a device/software and its placement that would provide
data security for the entire network of the School.
d. Suggest a device and the protocol that shall be needed to provide wireless Internet access
to all smartphone/laptop users in the campus of Multipurpose Public School, Bengaluru.
Name the device which is required for connecting computers in the blocks.

Answer:
a. Best wired medium- Twisted pair cable
Senior Junior

Admin Hostel

b. The server should be installed at Wing S(Senior) as per 80-20 rule i.e. maximum traffic
should be local and minimum traffic should pass over backbone.

c. Firewall.
d. Device: Wireless Access Point or Router or WiFi hotspot device or Wifi Dongle
Protocol: IEEE 802.11x or TCP/IP
e. Switch
Unit 3.
Database Management
Q1. Write the outputs of the SQL queries (i) to (iii) based on the relations Doctor and Place given
below:

Table : Doctor
DID DName Age Department Date_of_join Salary Gender

1 Rakesh 34 General 10/01/2017 120000 M


2 Parveen 31 Ortho 24/03/2008 200000 F
3 Satyajeet 32 ENT 12/12/2016 300000 M
4 Yogita 35 Heart 01/07/2015 400000 F
5 Chirag 42 General 05/09/2007 250000 M
6 Vijay 50 ENT 27/06/2008 300000 M
7 Kamlesh 44 Ortho 25/02/2017 210000 M
8 Seema 33 Heart 31/07/2018 200000 F

Table : Place
PID Department City
1 General Ajmer
2 Heart Udaipur
3 Ortho Jodhpur
4 ENT Jaipur

i. SELECT Department, count(*) FROM Doctor GROUP BY Department;


ii. SELECT Max(Salary),Min(salary),Max(Date_of_join ) FROM Doctor;
iii. SELECT Doctor.Dname, Doctor.Department, Place.city
FROM Doctor, Place
WHERE Doctor.Department = Place.Department AND
Place.city in (“Jaipur”,”Jodhpur”);

Answer:
i) General 2
Ortho 2
ENT 2
Heart 2
ii) 400000 120000 31/07/2018

iii) Parveen Ortho Jodhpur


Satyajeet ENT Jaipur
Vijay ENT Jaipur
Kamlesh Ortho Jodhpur

Q2. Write the outputs of the SQL queries (i) to (iii) based on the relations Doctor and Place given
below. write SQL queries for the following.

Table : Doctor
DID DName Age Department Date_of_join Salary Gender

1 Rakesh 34 General 10/01/2017 120000 M


2 Parveen 31 Ortho 24/03/2008 200000 F
3 Satyajeet 32 ENT 12/12/2016 300000 M
4 Yogita 35 Heart 01/07/2015 400000 F
5 Chirag 42 General 05/09/2007 250000 M
6 Vijay 50 ENT 27/06/2008 300000 M
7 Kamlesh 44 Ortho 25/02/2017 210000 M
8 Seema 33 Heart 31/07/2018 200000 F

Table : Place
PID Department City
1 General Ajmer
2 Heart Udaipur
3 Ortho Jodhpur
4 ENT Jaipur

a. To show all details about the doctors of ENT department.


b. To list the names of Male doctors who are in general department and getting above
120000 salary.
c. To list the name of all doctors and their date of joining in descending order.
d. To display Doctor’s name, salary, age for female doctors only.
e. To display no. of doctors available in each department.

Answer:
a. SELECT * FROM DOCTOR WHERE DEPARTMENT=’ENT’;
b. SELECT DNAME FROM DOCTOR WHERE GENDER=’M’ AND
DEPARTMENT=’GENERAL’ AND SALARY>120000;
c. SELECT DNAME,DATE_OF_JOIN FROM DOCTOR ORDER BY DATE_OF_JOIN
DESC;
d. SELECT DNAME,SALARY,AGE FROM DOCTOR WHERE GENDER=’F’;
e. SELECT DEPARTMENT,COUNT(*) AS “NO OF DOCTORS” FROM DOCTOR
GROUP BY DEPARTMENT;

Q3. Modern Public School is maintaining fees records of students. The database administrator
Aman decided that-

● Name of the database -School

● Name of the table – Fees

● The attributes of Fees are as follows:

Rollno - numeric

Name – character of size 20

Class - character of size 20

Fees – Numeric

Qtr – Numeric

Answer any four from the following questions:

(i) Identify the attribute best suitable to be declared as a primary key

(ii) Write the degree of the table.

(iii) Insert the following data into the attributes Rollno, Name, Class, Fees and Qtr in fees table.

(iv) Aman want to remove the table Fees table from the database School.

Which command will he use from the following:

a) DELETE FROM Fees;

b) DROP TABLE Fees;

c)DROP DATABASE Fees;

d) DELETE Fees FROM Fees;

(v) Now Aman wants to display the structure of the table Fees, i.e, name of the attributes and their
respective data types that he has used in the table. Write the query to display the same.

Answer:
i)Primary Key – Rollno

ii)Degree of table= 5

iii)Insert into fees values(101,’Aman’,’XII’,5000);

iv)DELETE FROM Fees


v)Describe Fees

Q4. Consider the table TEACHER given below. Write commands in SQL for (i) to (iii)

TEACHER
ID Name Department Hiredate Category Gender Salary
1 Taniya SocialStudies 03/17/1994 TGT F 25000
2 Abhishek Art 02/12/1990 PRT M 20000
3 Sanjana English 05/16/1980 PGT F 30000
4 Vishwajeet English 10/16/1989 TGT M 25000
5 Aman Hindi 08/1/1990 PRT F 22000
6 Pritam Math 03/17/1980 PRT F 21000
7 RajKumar Science 09/2/1994 TGT M 27000
8 Sital Math 11/17/1980 TGT F 24500

i. To display all information about teachers of Female PGT Teachers.

ii. To list names, departments and date of hiring of all the teachers in descending order of date of
joining.

iii. To count the number of teachers and sum of their salary department wise.

Answer:
i) SELECT * FROM TEACHER WHERE CATEGORY= ‘PGT’ AND GENDER= ‘F’;

ii) SELECT NAME, DEPARTMENT, HIREDATE FROM TEACHER ORDER BY HIREDATE


DESC;

iii) SELECT DEPARTMENT, COUNT(NAME), SUM(SALARY) FROM TEACHER GROUP BY


DEPARTMENT;

Q5. Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a table
COMPANY and CUSTOMER .

COMPANY

CID NAME CITY PRODUCTNAME

111 SONY DELHI TV

222 NOKIA MUMBAI MOBILE

333 ONIDA DELHI TV

444 SONY MUMBAI MOBILE

555 BLACKBERRY MADRAS MOBILE


666 DELL DELHI LAPTOP

CUSTOMER

CUSTID NAME PRICE QTY CID

101 Rohan Sharma 70000 20 222

102 Deepak Kumar 50000 10 666

103 Mohan Kumar 30000 5 111

104 Sahil Bansal 35000 3 333

105 Neha Soni 25000 7 444

106 Sonal Aggarwal 20000 5 333

107 Arjun Singh 50000 15 666

(i) To display those company name which are having price less than 30000.

(ii) To display the name of the companies in reverse alphabetical order.

(iii) To increase the price by 1000 for those customer whose name starts with ‘S’

(iv) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER

WHERE COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=”MOBILE”;

(v) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;

Answer:
i) SELECT COMPANY.NAME FROM COMPANY,CUSTOMER

WHERECOMPANY.CID = CUSTOMER.CID AND CUSTOMER.PRICE <30000;

ii) SELECT NAME FROM COMPANY ORDER BY NAME DESC;

iii) UPADE CUSTOMER

SET PRICE = PRICE+1000

WHERE NAME LIKE ‘S%’;

iv)

PRODUCTNAME CITY PRICE

MOBILE MUMBAI 70000

MOBILE MUMBAI 25000


v) 12

Q6. KVS RO Ranchi wants to store their students data using SQL to store data. The details is as
under:
Name of the Database: kvsroranchi
Name of the Table: Student
The attributes are as follows;
i. Std_id : Numeric
ii. Name: Character of size 20
iii. Class : character of size 4
iv. Marks : Numeric
v. City: Character of size 20

Std_id Name Class Marks City


101 Rohan XI 400 bhawanipatna
Aneeta
102 XII 390 Sambalpur
Chopra
103 Pawan Kumar IX 298 Cuttack
104 Sunit IX 376 Bhubaneswar
105 Sanjay VII 240 Bolangir
113 Anju Mahajan VIII 432 Berhampur

a. Identify the attribute best suitable to be declared as Primary Key


b. Which Command is used to create the database kvsroranchi.
c. Write SQL query to Insert the following record into the table Student:
106 Ranjan XI 430 Jajpur
d. Write the query to display the structure of the table.
e. We want to delete the city column from the table. What is the query for
that

Answer:
a. Std_id
b. Create database kvsroranchi;
c. Insert into student
Values(106, “ Ranjan’, “XI”, 430, “Jajpur”);
d. Desc student;
e. Alter table student
Drop city;

Q7. Write SQL queries (i) to (iii) based on the relation Graduate.

S.NO NAME STIPEND SUBJECT AVERAGE DIV


1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP. Sc. 68 I
CHEMISTR
3 DIVYA 300 62 I
Y
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
CEHMISTR
6 SABINA 400 55 II
Y
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP. Sc. 62 I
10 VIKAS 400 MATHS 57 II

i. Select subject, sum(Average) from Graduate GROUP BY Subject;


ii. Select Max(Stipend), Min(Stipend) from Graduate;
iii. Select Div, count(*) from Graduate Group By Div;

Answer:

i.
ii. Max(Stipend) Min(Stipend)
500 250
iii. DIV Count(*)
I8
II 2

Q8. Write SQL command for (i) to (v) on the basis of the table Employees & EmpSalary

Table: Employees
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
105 Harry Waltor Gandhi nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
24 Friends
244 Manila Sengupta New Delhi
street
300 Robert Samuel 9 Fif h Cross Washington
335 Ritu Tondon Shastri Nagar GZB
121 Harrison
400 Rachel Lee New York
St.
441 Peter Thompson 11 Red Road Paris

Table: EmpSalary

Empid Salary Benefits Designation


010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 salesman

a) To show firstname,lastname,address and city of all employees living in paris


b) To display the content of Employees table in descending order of Firstname.
c) To display the firstname,lastname and total salary of all managers from the tables Employee
and empsalary , where total salary is calculated as salary+benefits.
d) To display Empid, Designation and Salary of all employee from EmpSalary table whose benefits
more than 14000.
e) To display empid, First Name and city from employees table whose lastname start with s.

Answer: For correct query 1 mark. Step marking may be given as per CBSE rules.

Q9. Consider the following tables WORKERS and DESIG. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii) :

WORKERS
W_ID FIRSTNAME LASTNAME GENDER ADDRESS CITY
102 Sam Tones M 33 Elm St Paris
105 Sarah Ackerman F U.S. 110 New York
144 Manila Sengupta F 24 Friends New Delhi
Street
210 George Smith M 83 First Howard
Street
255 Mary Jones F 842,Vine Losantiville
Ave.
300 Robert Samuel M 9 Fifth Cross Washington
335 Henry Williams M 12 Moore Boston
Street
403 Ronny Lee M 121 Harrison New York
St.
451 Pat Thompson M 11 Red Road Paris

DESIG
W_ID SALARY BENEFITS DESIGNATION
102 75000 15000 Manager
105 85000 25000 Director
144 70000 15000 Manager
210 75000 12500 Manager
255 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
451 28000 7500 Salesman
(i) To display W_ID, Firstname, Address and City of all employees living in New York from the
table WORKERS.
(ii) To display the content of WORKERS table in ascending order of LASTNAME.
(iii) To display First Name, Worker ID and Address of male Workers only.
(iv) To display the Minimum salary among Managers and Clerks from the table DESIG.
(v) To display First Name and Salary from Workers and Desig Table for each worker.

Answer:
(i) SELECT W_ID,FIRSTNAME, ADDRESS, CITY FROM WORKERS WHERE CITY=’New York’;
(ii) SELECT * FROM WORKERS ORDER BY LASTNAME;
(iii) SELECT FIRSTNAME, W_ID, ADDRESS FROM WORKERS WHERE GENDER=’M’;
(iv) SELECT MIN(SALARY) FROM DESIG WHERE DESIGNATION IN(‘MANAGER’, ‘CLERKS’);
(v) SELECT FIRSTNAME, SALARY FROM WORKERS, DESIG WHERE
WORKERS.W_ID=DESIG.W_ID;

Q10.
Write the outputs of the SQL queries (i) to (iii) based on relations EMP and DESIG given below:

Table: EMP
E_ID Name Gender Age DOJ Designation
1 Om Prakash M 35 10/11/2009 Manager
2 Jai Kishan M 32 12/05/2013 Accountant
3 Shreya Sharma F 30 05/02/2015 Clerk
4 Rakesh Minhas M 40 15/05/2007 Manager
5 Himani Singh F 33 19/09/2010 Clerk

Table: DESIG
Salary E_ID DEPT_ID
45000 1 D101
35000 2 D102
45000 4 D101

i) SELECT Designation, count(*) FROM EMP GROUP BY Designation;


ii) SELECT AVG(Age) FROM EMP;
iii) SELECT EMP.Name, EMP.Designation,DESIG.Salary FROM EMP, DESIG WHERE
EMP.E_ID = DESIG.E_ID AND EMP.Age>35;

Answer:
(i)
Designation Count(*)
Manager 2
Accountant 1
Clerk 2
(ii) AVG(Age)
34
(iii)
Name Designation Salary
Rakesh Minhas Manager 45000

You might also like