Computer Science Stack Operations Support Material
Computer Science Stack Operations Support Material
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.
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.")
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.
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:
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‟:
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.
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:
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()
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 :
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()
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()
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:
OR
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()
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( )
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
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 :
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:
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.
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:
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:
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]
Answer:
L = [23, 13, 101, 6, 81, 9, 4, 1]
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)
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:
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:
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:
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]
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]
c=0
for i in L:
if i==n:
c=c+1
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
Output List : L = [54, 43, 89, 67, 34, 23, 12] # if the number passed is 4
Answer:
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’]
Answer:
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]
Answer:
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:
def disp(L1):
for i in L1:
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):
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)}
l=[ ]
if pid in emp:
l=emp[pid]
print(pid,”\t””\t””\t””\t”,l[0],”\t””\t”,l[1])
else:
Answer:
emp={1:(“Amit”,25000),2:(“Suman”,30000),3:(“Ravi”,36000)}
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())
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):
nm = input(“Enter name “)
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:
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
Answer:
str = input("Enter any String")
s1="aeiouAEIOU"
v=0
for i in str:
  if i in s1:
    v=v+1
print(v)
Answer:
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")
Answer:
Answer:
Q6. Write a program to accept a string from the user and count the frequency of alphabet ‘a’ and
‘c’.
Answer:
Q7. Write a program to display the last word of the string accepted from user.
Answer:
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:
str1 = ""
L=str.split()
for i in L:
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:
L = len(str)
if n > L :
else:
print(str[ : n ])
OUTPUT is:
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:
Q14. Accept a String from the user and display first two characters of each word in same line
separated by space.
Answer:
OUTPUT :
St Sl in Py
Q15. Write a program to display the largest word from the string.
Answer:
#Execution of program is :
Q17. Write a program to display the unique words from the string.
Answer:
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:
Q19. Write a program to accept a string and replace all spaces by ‘#’ symbol.
Answer:
.
#Execution of program
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 :
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
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:
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 :
#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:
str1 = ""
L=str.split( )
for i in L:
print(str1)
Q26. Write a program to accept a string and display the word which has vowel ‘a’ in it.
Answer:
.
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:
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:
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:
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:
if (str.find(substr)!=-1):
print("Substring is present")
else:
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:
L = len(str)
if n > L:
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:
str1 = ""
for i in str:
    str1 = str1 + i
     print(str1)
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:
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:
Q6.
5
44
333
2222
11111
Answer:
Q7.
5
54
543
5432
54321
Answer:
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:
Q15.
0
01
014
0149
0 1 4 9 16
Answer:
.
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:
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
Number of Computers
Accounts 25
Store 15
Packaging Unit 60
As a network expert, provide the best possible answer for the following queries:
ii) Suggest the most suitable place (i.e. buildings) to house the server of this organization.
a) Repeater b) Hub/Switch
iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.
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
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                    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:
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).
  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
                      Table : Place
                      PID    Department       City
                      1      General          Ajmer
                      2      Heart            Udaipur
                      3      Ortho            Jodhpur
                      4      ENT              Jaipur
Answer:
i)       General      2
         Ortho        2
         ENT          2
         Heart        2
ii)       400000      120000      31/07/2018
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
                      Table : Place
                      PID      Department      City
                      1        General         Ajmer
                      2        Heart           Udaipur
                      3        Ortho           Jodhpur
                      4        ENT             Jaipur
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-
Rollno - numeric
Fees – Numeric
Qtr – Numeric
(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.
(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
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
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’;
Q5. Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a table
COMPANY and CUSTOMER .
COMPANY
CUSTOMER
(i) To display those company name which are having price less than 30000.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
Answer:
i) SELECT COMPANY.NAME FROM COMPANY,CUSTOMER
iv)
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
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.
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
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
Answer:
 (i)
                   Designation     Count(*)
                   Manager         2
                   Accountant      1
                   Clerk           2
(ii)    AVG(Age)
          34
(iii)
         Name             Designation         Salary
         Rakesh Minhas    Manager             45000