computer python xii solutions 6-10 (1)

39
OSWAAL BOOKS “Oswaal House” 1/11, Sahitya Kunj, M.G. Road, AGRA-282002 Ph.: 0562-2857671, 2527781, Fax : 0562-2854582, 2527784 email : [email protected], website : www.oswaalbooks.com Published by : Class 12 Sample Question Papers Computer Science Strictly Based on Latest Syllabus Issued by CBSE for 2015 Examination solutions (Based on Python)

Upload: -

Post on 22-Dec-2015

36 views

Category:

Documents


2 download

DESCRIPTION

yes

TRANSCRIPT

OSWAAL BOOKS“Oswaal House” 1/11, Sahitya Kunj, M.G. Road, AGRA-282002Ph.: 0562-2857671, 2527781, Fax : 0562-2854582, 2527784

email : [email protected], website : www.oswaalbooks.com

Published by :

Class 12

Sample Question

Papers

Computer Science

Strictly Based on Latest Syllabus Issued by CBSEfor 2015 Examination

solutions

(Based on Python)

SOLUTIONSSAMPLE QUESTION PAPER–6

1. (a) Keyword arguments are related to the function calls. When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows us to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

You can also make keyword calls to the printme( ) function in the following ways:

# Function definition is here

def print ( str ):

print str

return

# Now you can call print function

print ( str = ”My string”)

[ 1 mark for answer and 1 mark for the example]

(b) [’jacket’, ’tshirt’, ’backpack’]

{’jacket’: ’fleece’, ’tshirt’: ’cotton’, ’backpack’: ’nylon’}

[1 mark for each correct line]

(c) 1

2

1

3

[½ mark for each correct answer]

(d) (10, 20, 30, 40, 50, 100, 200, 300)

[1 mark for correct answer and 1 mark for dry run]

(e) t=tuple( )

n=input(”Total number of values in tuple”)

for i in range(n):

a=input(”enter elements”)

t=t+(a,)

print ”maximum value=”,max(t)

print ”minimum value=”,min(t)

[1 mark for detecting error and 1 mark for correcting]

2. (a) l Capability to express closeness with the real-world models.

l Reusability – allows addition of new features to an existing one.

l Transitivity – changes in one class get automatically reflected across.

[ ½ mark for each feature. Any two features]

(b) Data hiding can be defined as the mechanism of hiding the data of a class from the outside world or to be precise, from other classes. Data hiding is achieved by making the members of the class private. Access to private members is restricted and is only available to the member functions of the same class. However, the public part of the object is accessible outside the class.

[ 2 marks for equivalent explanation]

2 ] OSWAAL CBSE Computer Science, Class - XII

(c) class SUPPLY: # constructor to create an object def __init__(self): #constructor self.FoodCode=0 self.FoodName=’ ’ self.FoodType=’ ’ self.Sticker=’ ’ def FoodIn(self): self.FoodCode=input(”Enter Food Code”) self.FoodName=raw_input(”Enter Food Name”) self.Sticker=raw_input(”Enter Sticker Colour”) def GetType(self): if self.Sticker==’GREEN’: self.FoodType=’Vegetarian’ elif self.Sticker==’YELLOW’: self.FoodType=’Contains Egg’ elif self.Sticker==’RED’: self.FoodType=’Non-Vegetarian’ else: self.FoodType=’Not Known’ def FoodOut(self): print”FoodCode”,self.FoodCode print”FoodName”,self.FoodName print”FoodType”,self.FoodType print”Sticker”,self.Sticker S=SUPPLY( ) S.FoodIn( ) S.GetType( ) S.FoodOut( ) [ 1 mark each for the functions] (d) class employee(object): # constructor to create an object def__init__(self): self.eno=0 self.name=’ ’ self.designation=’ ’ self.address=’ ’ self.phonenumber=0 def getdata(self): self.eno=input(”Enter Employee Number”) self.name=raw_input(”Enter Employee Name”) self.designation=raw_input(”Enter Employee Designation”) self.address=raw_input(”Enter Employee Address”) self.phonenumber=input(”Enter Employee Phone Number”)

SAMPLE QUESTION PAPER (Solutions) [ 3

def putdata(self): print”Employee Number”,self.eno print”Employee Name”,self.name print”Employee Designation”,self.designation print”Employee Address”,self.address print”Employee Phone Number”,self.phonenumber class salary(employee): # Salary details def __init__(self): super(salary,self).__init__( ) self.basic=0 self.DA=0 self.HRA=0 self.Gross=0 self.PF=0 self.tax=0 self.netpay=0 def getdata1(self): self.getdata( ) self.basic=float(raw_input(”Enter the basic pay”)) self.DA=float(raw_input(”Enter the DA”)) self.HRA=float(raw_input(”Enter the HRA”)) self.PF=float(raw_input(”Enter the PF”)) def calculate(self): self.Gross=self.basic+self.HRA+self.DA if self.Gross<100000: self.tax=0 elif self.Gross<500000: self.tax=self.Gross*0.10 elif self.Gross<1000000: self.tax=self.Gross*0.15 else: self.tax=self.Gross*0.20 self.netpay=self.Gross-self.PF-self.tax def display(self): self.putdata( ) print”Gross Income”,self.Gross print”Tax ”,self.tax print”Net Income”,self.netpay salaryobj=salary( ) num=int(raw_input(”Enter no. of employees:-”)) for i in range(0,num): salaryobj.getdata1( ) salaryobj.calculate( ) salaryobj.display( ) [2 marks each for each class definition]

4 ] OSWAAL CBSE Computer Science, Class - XII

3. (a) def selection_sort(DATA_LIST): for i in range(0,len(DATA_LIST)): min=i for j in range(i+1,len(DATA_LIST)): if DATA_LIST[j]<DATA_LIST[min]: min=j # swapping temp=DATA_LIST[min] DATA_LIST[min]=DATA_LIST[i] DATA_LIST[i]=temp print DATA_LIST DATA_LIST=[99 78 25 48 51 11] print”LIST BEFORE SORTING”,DATA_LIST selection_sort(DATA_LIST) [2 marks each for each selection sort function and 1 mark for correct invocation] (b) Solution : Given Data : Arr[15][20] W=4 B=? R=15 C=20 Lr = 0 Lc = 0 Address of Arr[3][2] = ? Address of Arr[5][2] = 1500. Address of an element (I,J) in row major = B+W(C(I-Lr)+(J-Lc)) Therefore, 1500 = B+4(20(5-0)+(2-0)) 1500 = B+4(20*5+2) 1500 = B+4*102 1500 = B+408 B = 1500-408 B = 1092 Address of Arr[3][2] = 1092+4(20*3+2) = 1092+4(62) = 1092+248 =1340. [1 Mark for correct formula OR correct substitution in the formula] [1 Mark for calculation of base address atleast one line after the substitution] [1 Mark for calculation of required address atleast one line after the substitution] (c) def summat(a,m,n): s=0 for i in range(m): for j in range(n): s+=a[i][j] return s a = [ [1,2,3],[4,5,6],[7,8,9]] print summat(a,3,3) [1 mark for for loops and 1 mark for correct invocation] (d) class queue: s=[ ] def insert(self): a=input(”Enter the number:”) queue.s.append(a)

SAMPLE QUESTION PAPER (Solutions) [ 5

def delete(self): if (a.s==[ ]): print ”Queue Empty” else: print ”Deleted element is: ”,queue.s[0] del queue.s[0] def display(self): l=len(queue.s) print”QUEUE CONTENTS” for i in range(0,l): print queue.s[i] a=queue( ) n=input(”Enter no. of numbers”) for i in range(n): a.insert( ) a.delete( ) a.display( ) [1 mark for init, 1 mark for delete and 1 mark for display functions] (e)

[1 mark for writing result alone. 1 mark for stack status]4. (a) Pickle module is used in serialization of data. This allows us to store data in binary form in the

file. Dump and load functions are used to write data and read data from file. [1 mark for equivalent explanation] (b) def countblankspace( ): fname=”story.txt” count=0 with open(fname,’r’)asf: for line in f: for word in line: for char in word: if char.isspace( ): count=count+1 print ”No. of spaces =”,count countblankspace( ) (c) from pickle import load,dump import os import sys fname=’TRAIN.dat’ choice=0

ifile=open(fname,’rb’)

6 ] OSWAAL CBSE Computer Science, Class - XII

start=raw_input(”Enter starting station”)

try:

while True:

t=load(ifile)

if t.start==start:

t.display( )

except EOFError:

pass

ifile.close( )

# Next search

ifile=open(fname,’rb’)

dest=raw_input(”Enter destination station”)

try:

while True:

t=load(ifile)

if t.dest==dest:

t.display( )

except EOFError:

pass

ifile.close( )

[2 marks for each search block]

5. (a) Number of rows- cardinality = (10-3) * 10 = 70

Number of columns – degree = 10

[1 mark for each correct degree and 1 mark for cardinality]

(b) (i) Select c.cust_id,c.cust_name,b.item,b.qty,b.price,b.Qty*b.price as billamount from Client c,bill b where c.cust_id = b.cust_id;

(ii) Select COUNT (*) from Bill where Item=’Pizza’ and Ord_date like ’%03%’

(iii) Select count (*),cust_id,SUM(qty*price) as totalamount from Bill group by Cust_id having SUM(qty*price) > 300

(iv) Select cust_name,city from client order by city

[1 mark for each correct query]

(c) Employee U Emp

E.No Ename Salary

111 Hari 20000

145 Saritha 86000

113 Rohan 85000

135 Madhu 35000

[ 2 marks for correct answer]

6. (a) = p’r’ + pq’ + q’r’(p + p’) As, q’r’1 = q’r’(p+p’)

= p’r’ + pq’ + pq’r’ + p’q’r’ Distributive theorem

= p’r’(1 + q’) + pq’(1 + r’) Taking out common factors

= p’r’ + pq’ As, 1+q’ = 1, 1+r’=1

[Each step ½ mark]

SAMPLE QUESTION PAPER (Solutions) [ 7

(b) The expression has two variables. The first term has only one variable. So to make it of two variables it can be multiplied by (Y + Y’), as Y + Y’ = 1. After multiplication the given logic expression can be written as :

X(Y + Y’) + XY’, as Y + Y’ = 1 or XY + XY’ + XY’ or XY + XY’ [1 mark for each term] (c)

[1 mark for each level expression] (d) K-map : The given expression is in POS. So the K-map design is Step 1 :

Step 2 :

Step 3 :

8 ] OSWAAL CBSE Computer Science, Class - XII

The final simplified expression is Y = (y+z).(w+x+y’).(w’+x+y).(w’+x’+y’+z)

[1 Mark for drawing the K-Map with right place values]

[1 Mark for groupings]

[½ Mark for each reduced term]

Note : Deduct ½ Mark for extra redundant term/groupings.

7. (a) Advantages of Star Topology :

(i) Failure of a single connection does not affect the entire network.

(ii) Fault detection is easier.

(iii) Access protocols being used in a Star network are very simple.

Disadvantages of Star Topology :

(i) large amount of cable is needed which increases the installation cost of the network.

(ii) The entire network is dependent on the central node. If the central node fails, the entire network goes down.

[1 mark for each relevant point]

(b) 80% of the traffic on a given network segment is local and only 20% need to move across sub networks. Congestions indicate that the network design isn’t following the 80-20 rule.

[1 mark for relevant answer]

(c) (v) ARPANET – Advanced Research Project Agency Network

(vi) PAN – Personal Area Network

(vii) NIU – Network Interface Unit

(viii) MAN – Metropolitan Area Network

[ ½ mark for each correct expansion]

(d) (v) Suggested cable layout

(vi) Block D might be the most suitable place to house the server of the school as it has the maximum number of computers.

(vii) Hub is required in all blocks as there are more than 1 computer. Repeater might be placed from B to D.

(viii) Wired Optical Fibre Communication could be used, as the distance is only 100 km. Satellite Communication could also be considered.

[ 1 mark for relevant answer]

(e) LAN

[1 mark for correct answer]

(f) (i) IRC (Internet Relay Chat) protocol is used for chatting. It provides chatting between a group or between two individuals.

(ii) VOIP stands for Voice Over Internet Protocol. It enables the transfer of voice using packet switched network rather than using public switched telephone network.

[1 mark for relevant answer]

nn

SAMPLE QUESTION PAPER–71. (a) Python provides a limited support to private members and this feature is called name mangling.

A name is prefixed with two leading underscores and no more than one trailing underscore.

(eg) __pvtrollno_

If we try to access this hidden attribute, then an error message will be displayed.

[1 mark for equivalent explanation and 1 mark for example]

(b) 5

6

6

The above example prints 5; then calling func1( ) prints 3. This is because func1 only increments a local x. Then func2( ) increments the global x and prints 6.

[1 mark for correct output and 1 mark for the dry run]

(c) [’Spring Break’, ’Summer Break’, ’Thanksgiving’, ’Winter Break’]

good food

get back to Colby

KeyError: ’winter break’

NameError: name ’WinterAtColby’ is not defined

KeyError: ’Columbus Day’ [ Since it is deleted]

[½ mark for each correct line of output]

[Also accept first 4 lines alone with explanation and last 2 lines would not be printed since it is a interpreted code]

(d) No error [1 mark]

Output:

10 [1 mark]

(e) 4

[1 mark for correct answer. 1 mark for dry run]

(f) These functions can send back a value and later resume processing from the place, where they left off. This allows the function to produce a series of values - over time, rather than computing them all at once and returning a list of values.

The primary difference between generator and normal function is that generator will yield a value instead of returning a value. It is the yield statement which allows the generator function to suspend the processing and send a value, simultaneously retaining the existing state of generator to resume processing over time.

2. (a) Abstraction and Encapsulation are complementary concepts. Through encapsulation only we are able to enclose the components of the object into a single unit and separate the private and public members. It is through abstraction that only the essential behaviours of the objects are made visible to the outside world.

So we can say that encapsulation is the way to implement data abstraction. In another example of class Student, only the essential information like roll no, name, date of birth, course, etc. of the student are visible. The secret information like calculation of grades, allotment of examiners, etc. is hidden.

[2 marks for equivalent explanation]

(b) 6

7

[1 mark for each correct answer]

10 ] OSWAAL CBSE Computer Science, Class - XII

(c) classAccount:

# constructor to create an object

def __init__(self,cust_name,accountno,act_type,balance):

self.cust_name=cust_name

self.accountno=accountno

self.act_type=act_type

self.balance=balance

# Displays customer details

def display(self):

print”Account Holder Name:”,self.cust_name

print”Account Number: ”,self.accountno

print”Account Type: ”,self.act_type,”Balance: Rs”,self.balance

def deposit(self,amt):

self.balance=self.balance+amt

print”Amount deposited”

def withdraw(self,amt):

if(self.act_type==’C’):

if(self.balance-amt>=1000):

self.balance=self.balance-amt

print”Amount withdrawn”

else:

print”Min. balance is Rs.1000 for current account”

else:

if(self.balance>=amt):

self.balance=self.balance-amt

print”Amount withdrawn”

else:

print”Amount exceeds balance”

[1 mark each for init , display, deposit and withdraw functions]

(d) classstudent(object):

# constructor to create an object

def __init__(self):

self.rno=0

self.m1=0

self.m2=0

def get(self):

self.rno=int(raw_input(”Enter the Roll no:”))

print”Enter 2 marks”

self.m1=int(raw_input(”Mark1?”))

self.m2=int(raw_input(”Mark2?”))

class sports(object):

# Sports mark

def__init__(self):

self.sm=0

SAMPLE QUESTION PAPER (Solutions) [ 11

defgetsm(self): self.sm=int(raw_input(”Enter the sports mark:”)) classstatement(student,sports): def __init__(self): super(statement,self).__init__( ) def display(self): tot=(self.m1+self.m2+self.sm); avg=tot/3; print”\n\n\t Roll No : ”,self.rno,”\n\t Total : ”,tot print”\tAverage : ”,avg obj=statement( ) obj.get( ) obj.getsm( ) obj.display( ) [1 mark each for the classes and 1 mark for invocation of functions]

3. (a) defselection_sort(DATA_LIST): for i in range(0,len(DATA_LIST)): min=i for j in range(i+1,len(DATA_LIST)): if DATA_LIST[j]<DATA_LIST[min]: min=j # swapping temp=DATA_LIST[min] DATA_LIST[min]=DATA_LIST[i] DATA_LIST[i]=temp print DATA_LIST NAME_LIST=[’Neena’,’Beeta’,’Reeta’,’Geeta’,’Seeta’] print”LIST BEFORE SORTING”,NAME_LIST selection_sort(NAME_LIST) LIST BEFORE SORTING [’Neena’, ’Beeta’, ’Reeta’, ’Geeta’, ’Seeta’] [’Beeta’, ’Neena’, ’Reeta’, ’Geeta’, ’Seeta’] [’Beeta’, ’Geeta’, ’Reeta’, ’Neena’, ’Seeta’] [’Beeta’, ’Geeta’, ’Neena’, ’Reeta’, ’Seeta’] [’Beeta’, ’Geeta’, ’Neena’, ’Reeta’, ’Seeta’] [’Beeta’, ’Geeta’, ’Neena’, ’Reeta’, ’Seeta’] [2 marks for selection sort algorithm. 2 marks for correct intermediate output] (b) Given Data : VAL[1…15][1…10] Word Length (W) = 4 Bytes Base Address of VAL(B) = 1500 VAL[12][9] = ? C = Total No of Columns R = Total No of Rows Lr = Least Row=1 Lc = Least Column=1

Address of an element (I,J) in row major = B + W ( C (I-Lr) + (J – Lc))

12 ] OSWAAL CBSE Computer Science, Class - XII

VAL [12][9] = 1500 + 4 (10 * (12-1) + (9-1)) = 1500 + 4 (10 * 11+8) = 1500 + 4 (118) = 1500 + 472 = 1972 [1 Mark for correct formula OR correct substitution in the formula] [1 Mark for calculation of required address at least one line after the substitution] [1 Mark for correct result] (c) list1 = [1,2,3] list2 = [4,5] fori in range(0,len(list2)): list1.append(list2[i]) print list1 [1 mark for for loop and 1 mark for append function] (d) The following algorithm shows the logic to convert an infix expression to an equivalent postfix

expression : 1. Create an empty stack and an empty postfix output string/stream. Scan the infix input

string/stream left to right. 2. If the current input token is an operand, simply append it to the output string (note the

examples above that the operands remain in the same order.) 3. If the current input token is an operator, pop off all the operators that have equal or higher

precedence and append them to the output string; push the operator onto the stack. The order of popping is the order of the output.

4. If the current input token is ’(’, push it onto the stack 5. If the current input token is ’)’, pop off all the operators and append them to the output string

until a ’(’ is popped; discard the ’(’. 6. If the end of the input string is found, pop all the operators and append them to the output

string. [½ mark for each step] (e)

Step Input symbols Action Stack status Intermediate

output

1 25 Push 25

2 8 Push 25 8

3 3 Push 25 8 3

4 – Pop twise (Binary operator) 25 8 – 3 = 5

5 5 Push 25 5

6 / Pop twise (Binary operator) 25/5 = 5

7 5 Push 5

8 6 Push 5 6

9 * Pop twise (Binary operator) 5*6 = 30

10 30 Push 30

11 10 Push 30 10

12 + Pop twise (Binary operator) 30 + 10 = 40

40 Push 40

No More Element 40 result [1 mark for showing result alone. 1 mark for stack status]

SAMPLE QUESTION PAPER (Solutions) [ 13

4. (a) Using ”with” ensures that all the resources allocated to file objects get deallocated automatically once we stop using the file.

[1 mark for equivalent definition]

(b) defCountDorM( ):

count=0

with open(’DELHI.txt’,’r ’) as f:

whileTrue:

line=f.readline( )

if not line: break

ifline[0]==’D’ or line[0]==’M’:

count=count+1

if count==0:

print”no line starts with D or M”

else:

print”count=”,count

CountDorM( )

[1 mark for opening file and while loop. ½ mark for condition check. ½ mark for count]

(c) filename = ”C:\Input.txt”

for line in reversed(open(filename).readlines( )):

printline.rstrip( )

[2 marks for correct answer or equivalent answer]

5. (a) Each table within the UNION should have :

l the same number of columns.

l similar data types and t.

l columns in the same order.

[2 marks for all 3 conditions]

(b) (i) SELECT Name from SPORTS where grade=’C’ or Grade2=’C’;

(ii) SELECT Count(*) from SPORTS where grade=’A’;

(iii) SELECT name from SPORTS where game1 = game2;

(iv) SELECT game,game2 from SPORTS where name like ’A%’;

(v) ALTER TABLE SPORTS ad (marks int(4);

(vi) UPDATE SPORTS set marks=20 where grade=’A’;

[1 mark for each query]

6. (a) Associative Laws of Boolean Algebra:

A.(B.C) = (A.B).C

OR

A+(B+C) = (A+B)+C

Verification of A.(B.C) = (A.B).C

A B C B+C A+(B+C) A+B (A+B)+C

0 0 0 0 0 0 0

0 0 1 1 1 0 1

0 1 0 1 1 1 1

0 1 1 1 1 1 1

14 ] OSWAAL CBSE Computer Science, Class - XII

1 0 0 0 1 1 1

1 0 1 1 1 1 1

1 1 0 1 1 1 1

1 1 1 1 1 1 1

[1 mark for stating any one associative law. 1 mark for any proof using truth table or algebraically]

(b)

[Full 2 marks for writing Correct Expression for Level III]

[Only 1½ mark, if Level II expressions are correctly written and Level III is wrong]

[½ mark if only Level I expressions are correct]

(c) A’.B’.C’ + A’.B.C + A.B.C’ + A.B.C

[1 mark for correct SOP expression]

[½ mark if ONLY one term of the expression is wrong]

(d)

F(A, B, C, D) = A.C’ + A’.B.C + B.C.D’

OR

F(A, B, C, D) = A.C’ + A’.B.C + B.C.D’

OR

F(A, B, C, D) = (A+C) . (B+C) . (A’+C’+D’)

OR

SAMPLE QUESTION PAPER (Solutions) [ 15

F(A, B, C, D) = (A+C) . (B+C’) . (A’+C’+D’) [½ mark for drawing the K-Map Correctly] [½ mark for placing the 1s/0s at correct positions] [½ Mark for grouping in the K-Map] [½ Mark for each reduced term] Note : Deduct ½ Mark for extra redundant term(s)/grouping(s).

7. (a) PAN (Personal Area Network) is a computer network organized around an individual person. Personal area networks typically involve a mobile computer, a cell phone and/or a handheld computing device such as a PDA. You can use these networks to transfer files including email and calendar appointments, digital photos and music.

(b) (i) Cable layout

(ii) Gamma block can house the server because it has the maximum number of computers. (iii) Repeater might not be required. Hub/Switch is needed in all the blocks. (iv) Radiowaves provide high speed connectivity in hilly regions. [1 mark for each answer] (c) Advantages : (1) Satellite communication is very economical keeping in mind the fact that the area

covered through satellite transmission is quite large. For e.g., satellites used for national transmission are visible from all parts of the country.

(2) Transmission and reception costs are independent of the distance between the two points. Disadvantages : (1) Placing the satellite into its orbit involves very high cost. (2) Since signals sent to a satellite are broadcasted to all receivers, so necessary security

measures have to be taken to prevent unauthorized tampering of data. (3) Transmission is affected by weather conditions like rain, thunderstorm, etc. [1 mark for advantage and 1 mark for disadvantage] (d) SMTP and POP3 are 2 examples of email protocols. SMTP stands for Simple Mail Transfer Protocol that allows transmission of email over the

Internet. Mostemail software is designed to use SMTP for communication purposes when sending email. It only works for outgoing messages.

Post Office Protocol 3 or POP3 is the third version of a widespread method of receiving email which receives and holds email for an individual until they pick it up.

[2 marks for equivalent explanation]

nn

SAMPLE QUESTION PAPER–81. (a) Python dynamically allocates and de-allocates memory. The 2-ways are :

(i) Reference Counting – counts the number of times an object is referenced by other objects. The garbage collector is triggered when an object’s reference count reaches 0.

(ii) Automatic Garbage Collection – is based upon a threshold of object allocations and de-allocations.

No. of allocations – No. of deallocations> Threshold

The garbage collector is run and the unused block of memory is reclaimed.

(b) Washington, Adams, Jefferson, Madison, and Monroe

(c) MONTHS [’Jan’, ’Feb’, ’Mar’, ’Apr’, ’May’, ’Jun’, ’Jul’, ’Aug’, ’Sep’, ’Oct’, ’Nov’, ’Dec’]

Mon

Tue

Wed

Thu

Fri

Sat

Sun

[1 mark for months and 1 mark for days]

(d) Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index, 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing new line from a string.

(e) 1

4

9

16

25

36

49

64

81

100

[2 marks for correct answer]

2. (a) Polymorphism is the ability for a message or data to be processed in more than one form. An operation may exhibit different behaviours in different instances. For e.g., consider the operation of addition of two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation.

[ 1 mark for explanation and 1 mark for example]

(b) 400

600

[1 mark for each correct line of output. ½ mark if dry run is shown but output is incorrect]

SAMPLE QUESTION PAPER (Solutions) [ 17

(c) from types import MethodType

class Person(object):

def __init__(self, name):

self.name = name

def play(self):

print ”%s is playing!” % self.name

p = Person(”Ram”)

p.play = MethodType(play, p)

p.play( )

In these examples, only the p instance will have play method, other instances of Person won’t. To accomplish this, we need to add the method to the class:

class Person(object):

def __init__(self, name):

self.name = name

def play(self):

print ”%s is playing!” % self.name

Person.play = play

(d) classAccomodation(object):

# constructor to create an object

def __init__(self):

self.roomno=0

self.roomtype=’ ’

self.roomrent=0.0

defgetroom(self):

self.roomno=input(”Enter the Room no:”)

self.roomtype=raw_input(”Enter the Room type:”)

self.roomrent=float(raw_input(”Enter Room Rent”))

classMeals(object):

# Meals class

def __init__(self):

self.mealcode=0

self.mealname=””

self.mealprice=0.0

defgetmeals(self):

self.mealcode=input(”Enter the meal code:”)

self.mealname=raw_input(”Enter the meal name:”)

self.mealprice=float(raw_input(”Enter the meal price”))

classCustomer(Accomodation,Meals):

def__init__(self):

super(Customer,self).__init__( )

self.custnum=0

self.custname=’ ’

self.address=’ ’

18 ] OSWAAL CBSE Computer Science, Class - XII

defgetCustomer(self):

self.custnum=input(”Enter the customer number”)

self.custname=raw_input(”Enter customer name”)

self.address=raw_input(”Enter customer address”)

defdisplaybill(self):

print”Customer Name:”,self.custname,”Address:”,self.address

print”RoomNo:”,self.roomno,”RoomType:”,self.roomtype,”RoomRent:Rs”,self. roomrent

print”Meal Name:”,self.mealname,”Price:”,self.mealprice

print”Total Amount Due:”,self.roomrent+self.mealprice

obj=Customer( )

obj.getCustomer( )

obj.getroom( )

obj.getmeals( )

obj.displaybill( )

[1 mark for each class definition]

3. (a) defselection_sort(DATA_LIST):

for i in range(0,len(DATA_LIST)):

min=i

for j in range(i+1,len(DATA_LIST)):

if DATA_LIST[j][2]>DATA_LIST[min][2]:

min=j

# swapping

DATA_LIST[min][0],DATA_LIST[i][0]=DATA_LIST[i][0],DATA_LIST[min][0]

DATA_LIST[min][1],DATA_LIST[i][1]=DATA_LIST[i][1],DATA_LIST[min][1]

DATA_LIST[min][2],DATA_LIST[i][2]=DATA_LIST[i][2],DATA_LIST[min][2]

printDATA_LIST

maxrange=input(”Enter Number of Students: ”)

Students=[ ]

for i in range(maxrange):

Details=[ ]

Details.append(input(”Enter roll_no”))

Details.append(raw_input(”Enter name”))

Details.append(input(”Enter marks”))

Students.append(Details)

print Students

selection_sort(Students)

[2 marks for selection sort algorithm and 1 mark for invocation]

(b) T[10][7] = 14000 + (10*7 + 10)*8

= 14000 + 80*8

= 14000 + 640

= 14640

[1 mark for substitution and 2 marks for correct answer]

SAMPLE QUESTION PAPER (Solutions) [ 19

(c) list = [1,2,3,4]

def Chop(list):

del(list[0])

del(list[len(list)-1])

return None

def middle(list):

Chop(list)

print list

middle(list)

[1 mark for Chop 1 mark for middle and 1 mark for invoking]

(d) (a) Front =2 Rear = 6

A B C D E

(b) Front = 4 Rear = 6

A B C D E

(c) Front = 4 Rear = (6+3) mod 6 = 3

X Y Z C D E

[ 1 mark for each correct answer]

(e)

Operator Scanned Stack Content

5 5

6 5, 6

6 5, 6, 9

+ 5, 15

80 5, 15, 80

5 5, 15, 80,5

* 5, 15, 400

– 5, –385

/ –1/77

The result is: -1/77

4. (a) 1. file = open(”xxx.txt”,’r+’)

2. file = file(”xxx.txt”,’r+’)

3. with open(”xxx.txt”,’r+’) as file:

(b) defCountUpper( ):

count=0

with open(’Story.doc’,’r ’) as f:

whileTrue:

line=f.readline( )

if not line:break

if line[0].isupper( ):

count=count+1

print ”No. of uppercase letters =”,count

20 ] OSWAAL CBSE Computer Science, Class - XII

CountUpper( )

[ 1 mark for opening file

1 mark for condition check]

(c) defbinAppend( ):

import pickle

file = open(’data.dat’,’ab’)

while True:

y = int(raw_input( ))

pickle.dump(y,file)

ans = raw_input(’want to enter more data Y/N’)

if ans.upper( )==’N’:break

file.close( )

binAppend( )

[1 mark for opening file in append mode

1 mark for using dump appropriately]

5. (a) Degree : The number of attributes (columns) in a relation determine the degree of a relation.

Cardinality : The number of tuples (rows) in a relation is called the cardinality of the relation.

[ 1 mark for each explanation]

(b) (a) select * from products where pname=’TV’ and stock>110;

(b) select company from products where warranty>2;

(c) select sum(price*stock) from PRODUCTS where company=’BPL’;

(d) selectcompany,COUNT(*) from products group by company;

(e) select count(*) from products where (20-NOV-2010- manufacture)/365>warranty;

(f) selectpname from products where (sysdate- manufacture)/365<warranty;

(g) (i) 4

(ii) 39000

[1 mark for each correct answer]

6. (a) The above expression can be written as :

X+X’Y+Y’+XX’Y+Y’X’Y

=X+X’Y+Y’ as XX’=0, and YY’=0

=X+Y+Y’ as X+X’Y=X+Y

=X+1 as Y+Y’=1

=1 as X + 1=1

(b) To convert the above expression into canonical form, the following identity can be used :

X + Y = (X + Y + Z) (X + Y + Z’)

Applying the above identity, the given logic expression can be written as

(A + B + C) (A + B + C’) (A + B + C) (A’ + B + C)

= (A + B + C) (A + B + C’) (A’ + B + C)

(c) Step 1 : Expression is already in POS.

Step 2 : Logic Diagram – (X OR Y) AND (Y OR Z) AND (Z OR X).

Step 3 : Replace all gates by NOR gates.

(X NOR Y) NOR (Y NOR Z) AND (Z NOR X)

SAMPLE QUESTION PAPER (Solutions) [ 21

(d)

Quad 1 = a’c’ , Quad 2 = ab’ , Pair 1 is a’bd, Pair 2 is b’cd’ , Pair 3 is acd’

The simplified form is: a’c’ + ab’ + a’bd + b’cd’ + acd’

7. (a) (i) Modulator Demodulator

(ii) Frequency Modulation

[1 mark for each expansion]

(b) (III) Bus topology

(IV) Star topology

[½ mark for each correct answer]

(c) (III) LAN

(IV) Router

[1 mark for each correct answer]

(d) Client side scripts: Java script / VB script / Peril Tcl/Tk / REXX.

Server side scripts: JSP / ASP / PHP / CGI / Perl

[1 Mark for writing one correct Client side scripting language name]

[1 Mark for writing one correct Server side scripting language name]

(e) (i) Operating someone’s Internet banking account, without his knowledge.

[1 Mark for writing correct option]

22 ] OSWAAL CBSE Computer Science, Class - XII

(f) Free Software : The S/W’s is freely accessible and can be freely used, changed, improved, copied and distributed by all and payments are needed to make for free S/W.

Freeware : Freeware are the software freely available, which permit redistribution but not modification (and their source code is not available). Freeware is distributed in Binary Form (ready to run) without any licensing fees.

[1 mark for each explanation]

(g) On the Internet, the word ”protocol” refers to a set of rules for communicating. Two programs or computers that follow the same rules are able to exchange information, even if they don’t run the same operating system and are not made by the same company.

The protocol used for searching information from Internet using the Internet Browser is TCP/IP or HTTP.

[1 mark for each explanation]

nn

SAMPLE QUESTION PAPER–91. (a) User classes are considered mutable. Python doesn’t have (absolutely) private attributes, so you

can always change a class. [1 mark for correct answer with reason] (b) If the class does not contain any statements i.e. it is a class without any attributes or methods

, then a keyword ’pass’ is given within the body of the class. In the above example ’pass’ is a keyword. Giving pass in the class definition means that the class doesn’t define any method or attribute. But since there needs to be something in the definition, so you use pass. It’s a statement that does nothing.

Output : 2 3 [1 mark for explanation and ½ mark for each line of output] (c) 4 12 24 [1 mark for each correct answer] (d) UnboundLocalError: local variable ’ptr’ referenced before assignment [1 mark for identifying error. 1 mark for giving the explanation] (e) An abstract method is a method declared in a parent class, but not implemented in it. The

implementation of such a method can be given in the derived class. class circle(object): def get_radius(self): [1 mark for definition and 1 mark for the example]

2. (a) Binding is the process of linking the function call to the function definition. The body of the function is executed when the function call is made. Binding can be of two types :

Static Binding: In this type of binding, the linking of function call to the function definition is done during compilation of the program.

Dynamic Binding: In this type of binding, linking of a function call to the function definition is done at run time. That means the code of the function that is to be linked with function call is unknown until it is executed.

[1 mark for each correct answer] (b) Self is an object reference to the object itself, therefore, they are same. Python methods are not

called in the context of the object itself. Self in Python may be used to deal with custom object models.

(c) classemployee(object): def__init__(self,no,name,age): self.no=no self.name=_name____ #completethestatement self.age=_age_____ #completethestatement defprintval(self): print”Number:”,self.no print”Name :”,self.name print”Age :”,self.age classpay(object): def__init__(self,dept,salary): #completethedefinition

24 ] OSWAAL CBSE Computer Science, Class - XII

self.dept=dept

self.salary=salary

defdisplay(self): #completethedefinition

self.printval( )

printself.dept

printself.salary

[ ½ mark for each correct line ]

(d) Single inheritance : When a subclass inherits from only one base class, and there are only 2 classes in this relationship, then it is known as single inheritance.

Multilevel inheritance : When a subclass inherits from a class that itself inherits from another class, it is known as multilevel inheritance.

Multiple inheritance : When a subclass inherits from multiple base classes it is known as multiple inheritance.

Hierarchical inheritance : When many subclasses inherit from a single base class it is known as hierarchical inheritance.

SAMPLE QUESTION PAPER (Solutions) [ 25

Hybrid inheritance : Hybrid inheritance combines 2 or more forms of inheritance.

[ ½ mark for each type of inheritance. ½ mark if all 5 types explained] (e) (I) getattr(obj, name[, default]) (II) delattr(obj, name) [1 mark for each correct answer]

3. (a) n=input(”Enter no. of values”) num=[ ] flag=0 for i in range(n): number=input(”Enter the number”) num.append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j]=num[j],num[i] j=j-1 else: break print num [1 mark for either getting the values or initializing the list 2 marks for correct swapping] (b) Python lists are actually arrays of variable length. The elements of a list are of heterogeneous

types which means they are of different data types. Hence, [4,”Raja”, 80.55, ’A’] is a valid list. This is possible because in Python language, technically pointers, and not objects are stored in the form of an array. So a list in Python is an array that contains elements (pointers to objects) of a specific size only and this is a common feature of all dynamically typed languages.

For implementation of a list, a contiguous array of references to other objects is used. Python keeps a pointer to this array and the array’s length is stored in a list head structure. This makes indexing of a list independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized.

[2 marks for equivalent explanation] (c) defprintlist(s): i=0 for i in range(len(s)): print i,s[i]

i=0

phonenumbers=[’9840012345’,’9840011111’,’9845622222’,’9850012345’,’9884412345’]

26 ] OSWAAL CBSE Computer Science, Class - XII

flag=0

number=raw_input(”Enter the phone number to be searched”)

number=number.strip( )

try:

i=phonenumbers.index(number)

if i>=0:

flag=1

exceptValueError:

pass

if (flag<>0):

print”\nphone number found in phonebook at index”,i

else:

print”\nphone number not found in phonebook”

print”\nPHONEBOOK”

print list(phonenumbers)

[ 1 mark for creating dictionary

1 mark for function]

(d) Step 1 : Start

Step 2 : Check FRONT and REAR value, if both the values are -1, then FRONT and REAR are incremented by 1 otherwise Rear is incremented by one.

Step 3 : Add new element at Rear. (i.e.) queue[Rear]=new element.

Step 4 : Stop

[2 marks for the correct algorithm. Deduct 1 mark if program written instead of algorithm]

(e)

Operator/Operand Stack Calculation Meaning

6 6 Operand pushed to stack

5 65 Operand pushed to stack

2 652 Operand pushed to stack

* 610 5*2=10 Pop last two operands, perform the operation and push the result in stack

10 610 10 Operand pushed to stack

4 6104 104 Operand pushed to stack

+ 61014 10+4=14 Pop last two operands, perform the operation and push the result in stack

+ 624 10+14=24 Pop last two operands, perform the operation and push the result in stack

– –18 6–24=–18 Pop last two operands, perform the operation and push the result in stack

The answer is – 18

[1 mark for stack status

1 mark for result]

4. (a) Whenever we have to write a sequence of string / data type, we will use writelines( ), instead of write( ).

[1 mark for correct answer]

SAMPLE QUESTION PAPER (Solutions) [ 27

(b) def countalpha( ):

fname=” NOTES.txt”

count=0

with open(fname,’r’) as f:

for line in f:

for word in line:

for char in word:

if char.isalpha( ):

count=count+1

print count

countalpha( )

[1 mark for opening file and 1 mark for splitting and counting ]

(c) defbinfile( ):

importpickle # line1

file=open(’data.dat’,’wb’) # line2

whileTrue:

x=raw_input(”Enter name”) # line3

pickle.dump(x,file) # line4

ans=raw_input(’want to enter more data Y / N’)

if ans.upper( )==’N’:break

file.close( ) # line5

print”Reading from file”

file=open(’data.dat’,’rb’) # line6

try: # line7

whileTrue: # line8

y=pickle.load(file) # line9

print y # line10

except EOFError: # line11

pass

file.close( )

binfile( )

[1 mark for opening the files

1 mark for using the dump function properly

1 mark for using load function properly]

5. (a) Cartesian Product (binary operator): It operates on two relations and is denoted by X. For example Cartesian product of two relations R1 and R2 is represented by R = R1 X R2. The degree of R is equal to sum of degrees of R1 and R2. The cardinality of R is the product of cardinality of R1 and cardinality of R2.

Example :

Relation : R1

Roll No Student Name Class

1 Akash XII

4 Debakar X

10 Rishi XI

28 ] OSWAAL CBSE Computer Science, Class - XII

Relation : R2

Teacher Code Teacher Name

102 Ms Rinee

309 Mr Tanmoy

Resultant : R = R1 × R2

Col1 Col2 Col3 Col4 Col5

1 Akash XII 102 Ms Rinee

1 Akash XII 309 Mr Tanmoy

4 Debakar X 102 Ms Rinee

4 Debakar X 309 Mr Ranmoy

10 Rihsi XI 102 Ms Rinee

10 Rishi XI 309 Mr Ranmoy

Union (binary operator) : It operates on two relations and is indicated by U.

For example, R=R1 U R2 represents union operation between two relations R1 and R2. The degree of R is equal to degree of R1. The cardinality of R is sum of cardinality of R1 and cardinality of R2.

Following have to be considered for the operation R1 U R2 :

(i) Degree of R1 = Degree of R2

(ii) jth attribute of R1 and jth attribute of R2 must have a common domain.

Example :

Relation : R1

Student_ID Name

R490 Fatima

R876 Faraz

R342 Gauri

Relation : R2

Student_ID Student_Name

S123 Rekha

S456 Tushi

Resultant Relation : R = R1 U R2

Column1 Column2

R490 Fatima

R876 Faraz

R342 Gauri

S123 Rekha

S456 Tushi

[1 Mark for explaining Union correctly]

[1 Mark for explaining Cartesian Product correctly]

(b) (i) SELECT FROM WORKER ORDER BY DOB DESC;

(ii) SELECT NAME, DESIG FROM WORKERWHERE PLEVEL IN (’P001’, ’P002’) ;

OR

SELECT NAME, DESIG FROM WORKERWHERE PLEVEL = ’P001’ OR PLEVEL= ’P002’;

SAMPLE QUESTION PAPER (Solutions) [ 29

(iii) SELECT * FROM WORKERWHERE DOB BETWEEN ’19-JAN-1984’ AND ’18-JAN-1987’

OR

SELECT * FROM WORKERWHERE DOB >= ’19-JAN-1984’ AND DOB<=’18-JAN-1987’;

OR

SELECT * FROM WORKERWHERE DOB > ’19-JAN-1984’ AND DOB<’18-JAN-1987’ ;

(iv) INSERT INTO WORKERVALUES (19, ’Daya Kishore’, ’Operator’ , ’P003’ , ’11-Jun-1984’);

[1 Mark for correct query]

[½ Mark for partially correct answer]

(c) OUTPUTS :

(i)

COUNT (PLEVEL) PLEVEL

1 P001

2 P002

3 P003

(ii)

MAX (DOB) MIN (DOJ)

12-Jul-1987 13-Sep-2004

(iii)

NAME PAY

Radhe Shyam 26000

Chander Nath 12000

OR

P.ECode does not exist

(iv)

PLEVEL PAY+ALLOWANCE

P003 118000

[½ Mark for correct output]

6. (a)

X Y X’ Y’ X’Y X.Y’ X’.Y’ X’Y + X.Y’ + X’Y’ (X’ + Y’)

0 0 1 1 0 0 1 1 1

0 1 1 0 1 0 0 1 1

1 0 0 1 0 1 0 1 1

1 1 0 0 0 0 0 0 0

Hence proved

[ ½ mark for each 2 columns of the truth table]

(b) H = p (0,5,6)

= (A+B+C).(A’+B+C’).(A’+B’+C)

[1 mark for the correct answer]

30 ] OSWAAL CBSE Computer Science, Class - XII

(c)

[1 mark for intermediate expression and 1 mark for final expression.

2 marks for final answer alone]

(d)

3 quads and 2 pairs

F(a,b,c,d) = b’d’ + a’c’ + ab’ + a’bd + acd’

[1 mark for correct marking of 1’s

2 marks for grouping and writing the simplified expression]

[Deduct ½ mark for each wrong term]

7. (a)

Bus topology Star Topology

[1 mark for each correct diagram]

(b) A switch is a device that is used to break a network into different sub-networks called subnet or LAN segments. This prevents traffic overloading on the network. Switches are another fundamental part of many networks because they speed up things. They allow different nodes of a network to communicate directly with one another in a smooth and efficient manner. In simple terms, a network switch is a small hardware device that joins multiple computers together within one local area network (LAN).

[2 marks for equivalent explanation]

(c) Wi-Fi cards are small and portable cards that allow your desktop or laptop computer to connect to the internet through a wireless network. Wi-Fi transmission is through the use of radio waves. The antenna transmits the radio signals and these signals are picked up by Wi-Fi receivers such as computers and cell phones equipped with Wi-Fi cards. These devices have to be within the range of a Wi-Fi network to receive the signals. The Wi-Fi card then reads the signals and produces a wireless internet connection. Once a connection is established between a user and

SAMPLE QUESTION PAPER (Solutions) [ 31

the network, the user will be prompted with a login screen and password, if the connection being established is a secure connection.

[2 marks for equivalent explanation]

(d) Gateway

[1 mark for the correct answer]

(e) Bandwidth refers to the range of frequencies available for transmission of data. It is expressed as the difference in Hertz(Hz) between the highest frequency and the lowest frequency.

In computer networking, bandwidth is often used as a synonym for data transfer rate.

The data transfer rate (DTR) is the amount of data in digital form that is moved from one place to another in a given time on a network. The greater the bandwidth of a given medium, the higher is the data transfer rate. Data transfer rate is often measured in bits per second (bps), although the unit baud , which is one bit per second is also used.

[1 mark each for equivalent definition of bandwidth and DTR]

(f) Spam means endless repetition of worthless text. In other words, unwanted messages or mails are known as Spam. At times internet is flooded with multiple copies of the same message, it is nothing but spam. Most spam is commercial advertising. In addition to wasting people’s time, spam also eats up a lot of network bandwidth.

A firewall is hardware or software based network security system. It prevents unauthorized access (hackers, viruses, worms, etc.) to or from a network.

Firewalls are used to prevent unauthorized internet users to access private networks connected to the Internet. All data entering or leaving the Intranet pass through the firewall, which examines each packet and blocks those that do not meet the specified security criteria.

[1 mark each for equivalent definition]

(g) GSM - Global System for Mobile Communication.

GPRS - General Packet Radio Service.

[1 mark for each expansion]

(h) Free software means that users have the freedom to run, copy, distribute, study, change and improve the software. With these freedoms, the users (both individually and collectively) control the program and what it does for them.

”Free software” does not mean ”non-commercial”. A free program must be available for commercial use, commercial development, and commercial distribution.

Open Source Software refers to a program or software in which the source code (the form of the program when a programmer writes a program in a particular programming language) is available to the general public for use and/or modification from its original design free of charge. Open source code is typically created as a collaborative effort in which programmers improve upon the code and share the changes within the community.

[1 mark for each correct explanation]

nn

SAMPLE QUESTION PAPER–101. (a) A tuple is immutable i.e. cannot be changed. It can be operated on only. But a list is mutable.

Changes can be done internally to it.

tuple initialization: a = (2, 4, 5)

list initialization: a = [2, 4, 5]

[1 mark for each explanation]

(b) 14 times

[1 mark for correct answer]

(c) 3

[1 mark for correct answer . 1 mark for dry run]

(d) u

ueberry

blu

blueberry

blueberry

[½ mark for each statement]

(e) If there is a function with many parameters and we want to specify only some of them in function call, then value for such parameters can be provided by using their name instead of the position. This is called keyword argument.

(eg) def simpleinterest(p, n=2, r=0.6)

def simpleinterest(p, r=0.2, n=3)

[1 mark for definition and 1 mark for example]

2. (a) A constructor is a special method that is used to initialize the data members of a class. In python, the built in method __init__ is a sort of constructor.

In Python, the first argument of every class method, including __init__, is always a reference to the current instance of the class and by convention, this argument is always named ’self ’. In case of __init__, self refers to the newly created object or the instance whose method was called. The __init__ method never returns a value.

[2 marks for equivalent definition]

(b) class Shape(object):

def __init__(self):

pass

def area(self):

return 0

class Square(Shape):

def __init__(self, l):

Shape.__init__(self)

self.length = l

def area(self):

returnself.length*self.length

aSquare= Square(3)

print aSquare.area( )

[ 2 marks for correct definition. 1 mark for invocation]

SAMPLE QUESTION PAPER (Solutions) [ 33

(c) An abstract method is a method defined in a base class, but it may not provide any implementation. An abstract method can also have an implementation, but it can only be invoked with super from a derived class.

class Animal:

@abstractmethod

defsay_something(self):

return ”I’m an animal!”

class Cat(Animal):

defsay_something(self):

s = super(Cat, self).say_something( )

return ”%s - %s” % (s, ”Miauuu”)

[1 mark for definition and 1 mark for example]

(d) classEmployee(object):

# constructor to create an object

def__init__(self):

self.eno=0

self.name=’’

defGetdata(self):

self.eno=input(”Enter the Employee no:”)

self.name=raw_input(”Enter the Employee Name:”)

defPrintdata(self):

print”Employee Number”,self.eno

print”EmployeeName”,self.name

classpayroll(Employee):

def__init__(self):

super(payroll,self).__init__( )

self.salary=0

defInputdata(self):

self.Getdata( )

self.salary=float(raw_input(”Enter the salary:”))

defOutdata(self):

self.Printdata( )

print”Salary is”,self.salary

classleave(payroll):

def__init__(self):

super(leave,self).__init__( )

self.Noofdays=0

defacceptdata(self):

self.Inputdata( )

self.Noofdays=input(”Enter leave days”)

defshowdata(self):

self.Outdata( )

print”No. of leave days”,self.Noofdays

34 ] OSWAAL CBSE Computer Science, Class - XII

leaveobj=leave( )

leaveobj.acceptdata( )

leaveobj.showdata( )

[1 mark for each class definition and 1 mark for invocation]

3. (a) freq = { } # frequency of words in text

line = raw_input( )

for word in line.split( ):

freq[word] = freq.get(word,0)+1

words = freq.keys( )

words.sort( )

for w in words:

print ”%s:%d” % (w,freq[w])

[1 mark for using dictionary. 1 mark for logic]

(b) set1=set([1,3,6,78,35,55])

set2=set([12,24,35,24,88,120,155])

set1 &= set2

li=list(set1)

print li

[1 mark for correct declaration of the sets. I mark for logic]

(c) defremoveDuplicate( li ):

newli=[ ]

seen = set( )

for item in li:

if item not in seen:

seen.add( item )

newli.append(item)

return newli

li=[12,24,35,24,88,120,155,88,120,155]

print removeDuplicate(li)

[1 mark for using set. 1 mark for append]

(d) For searching in sorted lists we can use binary search for efficiency.

defbinary_search(DATA_LIST, ELEM, low, high):

low=0

high=len(DATA_LIST)

while(low<high):

mid=(int)(low+high/2)

if DATA_LIST[mid]==ELEM:

print ”Element found at”

print mid

break

if DATA_LIST[mid]<ELEM:

low=mid+1

if DATA_LIST[mid]>ELEM:

SAMPLE QUESTION PAPER (Solutions) [ 35

high=mid-1

if low >= high

print ”ELEMENT NOT FOUND”

[2 marks for the algorithm. 1 mark for mentioning binary search]

(e)

Operator/Operand Stack Result (List) Meaning

A A Operand moved to result list

/ / A Operand pushed to stack

B / AB Operand moved to result list

^ /^ AB Operand pushed to stack

C /^ ABC Operand moved to result list

– – ABC^/As compared to – operator, ^ and / has higher priority, so pop both operators and add them to the result list

D – ABC^/D Operand moved to result list

ABC^/D– Expression empty-Final Result

The resultant postfix expression is ABC^/D-

[1 mark for stachtatus. 1 mark for final expression]

(f)

Result = 10.

[1 mark for stachtatus. 1 mark for final expression]

4. (a) tell( ) method returns an integer giving the current position of object in the file. The integer returned specifies the number of bytes from the beginning of the file till the current position of file object.

It’s syntax is :

fileobject.tell( )

seek( ) method can be used to position the file object at particular place in the file. It’s syntax is :

fileobject.seek(offset [, from_what])

here offset is used to calculate the position of fileobject in the file in bytes. Offset is added to from_what (reference point) to get the position. Following is the list of from_what values:

Value reference point

0 beginning of the file

1 current position of file

2 end of file

default value of from_what is 0, i.e. beginning of the file.

[2 marks for equivalent definition]

(b) defcountchar( ):

fname=”story.txt”

count=0

36 ] OSWAAL CBSE Computer Science, Class - XII

c=raw_input(”Enter the character to search for”)

withopen(fname,’r’)asf:

for line in f:

for word in line:

for char in word:

if char.strip( )==c.strip( ):

count=count+1

print”No. of occurencesof”,c,”=”,count

countchar( )

[1 mark for getting character and opening file. 1 mark for checking for the character]

(c) defbinfile( ):

import pickle # line1

file=open(’data.dat’,’wb’) # line2

whileTrue:

x=int(raw_input(”Enter number”)) # line3

pickle.dump(x,file) # line4

ans=raw_input(’want to enter more data Y / N’)

if ans.upper( )==’N’:break

file.close( ) # line5

print”Reading from file”

file=open(’data.dat’,’rb’) # line6

try: # line7

whileTrue: # line8

y=pickle.load(file) # line9

print y # line10

except EOFError: # line11

pass

file.close( )

binfile( )

[1 mark for opening file , 1 mark for dump and 1 mark for load – proper usage of functions]

5. (a) (i) S_ID

(ii) Domain of the column LASTNAME is any string which contain only alphabets (upper or Small case).

[1 mark for each correct answer]

(b) (i) SELECT * FROM CUSTOMER_DETAILS WHERE ACCT_TYPE IN (’SAVING’,’CURRENT’)

(ii) SELECT CUT_NAME, DOJ FROM CUSTOMER_DETAILS ORDER BY DOJ DESC

(iii) SELECT * FROM CUSTOMER_DETAILS WHERE DOJ > ’1998-05-31’

(iv) SELECT * FROM CUSTOMER_DETAILS WHERE (GENDER = ’F’ and ACCULT_ANT > 1025000)

(v) SELECT * FROM CUSTOMER_DETAILS WHERE CUT_NAME LIKE ’_____’

(vi) SELECT DISTINCE ACCT_TYPE FROM CUSTOMER_DETAILS

[1 mark for each correct query. ½ mark for partial answer]

6. (a) X.(Y+Z) = XY + XZ

X+(Y.Z) = (X+Y).(X+Z)

SAMPLE QUESTION PAPER (Solutions) [ 37

Proof: X.(Y+Z) = XY + XZ

X Y Z Y+Z XY XZX (Y+Z) XY+XZ

0 0 0 0 0 0 0 0

0 0 1 1 0 0 0 0

0 1 0 1 0 0 0 0

0 1 1 1 0 0 0 0

1 0 0 0 0 0 0 0

1 0 1 1 0 1 1 1

1 1 0 1 1 0 1 1

1 1 1 1 1 1 1 1

[1 mark for stating the laws . 1 mark for truth table]

(b) Step 1 : Expression : AB + BC + CD . It is already in SOP.

Step 2 : Logic Diagram : (A AND B) OR (B AND C) OR (C AND D).

Step 3 : NAND Diagram : Replace each gate by NAND gate.

(A NAND B) NAND (B NAND C) NAND (C NAND D)

[1 mark for step 1 and 2. 1 mark for step 3]

(c) Taking LHS

= (A+B).(A’+C). (B+C)

= (A+B).(A’+C). (B+C). (B+C) by Idempotency

= (A+B).(B+C).(A’+C). (B+C) by Commuting

= (B+A).(B+C).( C+A’). (C+B) by Commuting

= (B+A.C) .( C+ A’B ) by Distributive

= (B+AC).C + (B+AC). A’B by Distribution

= B.C + A.C.C + B. A.’.B + A.C.A’B by Distribution

= B.C + A.(C.C) + (B.B). A’+ C. (A. A’).B by Associativity and Idempotency

= B.C + A.C + B.A’+ 0 by Complement and Idempotency

= (B+A).C + B.A’+ A. A’ by Complement and Distributive

= (B+A).C + (B+A).A’ by Distributive

= (B+A).(C + A’) by Distributive

= (A+B). (A’+C) by Commuting

Hence proved.

[1 mark for the first few lines. 1 more mark for the full proof]

38 ] OSWAAL CBSE Computer Science, Class - XII

(d)

1 octet and 1 quad

F(a,b,c,d) = c’ + bd

[1 mark for marking 1’s. 1 mark for grouping and 1 mark for the final answer]

[Reduce 1 mark if octet not marked]

7. (a) (i) Since there is a single common data path connecting all the nodes, the bus topology uses a very short cable length which considerably reduces the installation cost.

(ii) The linear architecture is very simple and reliable.

(iii) Additional nodes can be easily connected to the existing bus network at any point along the length of the transmission medium.

[1 mark for each valid point–2]

(b) A Router is a network device that works like a bridge to establish a connection between two networks but it can handle networks with different protocols. For example, a router can link an Ethernet network to a mainframe or to internet. If the destination is unknown to the router, it sends the traffic to another router which knows the destination. The data is sent to the router which determines the destination address (using logical address) and then transmits the data accordingly. Hence, routers are smarter than hubs and switches.

[2 marks for equivalent definition]

(c) PAN

[1 mark for the correct answer]

(d) A communication channel is a medium that is used in the transmission of a message from one point to another. In simple terms we can say that it is a pathway over which the data is transferred between remote devices.

Depending on their speed, we have three broad categories of communication channels - narrow band which is slow and used for telegraph lines and low speed terminals; voice band used for ordinary telephone communication and broad band which is fastest and is used for transmitting large volumes of data at high speeds.

[1 mark for definition and 1 mark for mentioning the types]

(e) Worm is a malicious program and works independently unlike virus. It checks for a security hole in the network and starts replicating itself.

Trojan horse contains hidden malicious functions. They trick the user in believing them as legitimate programs. They do not replicate.

[1 mark for each correct answer]

(f) URL: http://www.ABCSchool.in/home.aboutus.hml

Domain name: ABCSchool.in

[½ mark for each correct answer]

(g) Client side scripting language : JAVASCRIPT/VBSCRIPT

[1 mark for correct answer]

nn