Computer Science - XII
Section B (Python)
1.
a) What are sets in Python? Differentiate
sets and dictionaries. [2]
b) Observe
the following Python functions and write the name(s) of the module(s) to which
they belong: [1]
a. uniform()
b. findall()
c)Rewrite the following code after removing errors. Underline
each correction and write the output after correcting the code: [2]
class First():
def__init__(self):
print "first":
class Second(object):
def__init__(self):
print "second"
class Third(First,Second):
def__init__(self):
First.__init__(self):
Second.__init__(self):
print"Done"
t=Third()
d)
Find the output of the following Python program: [3 ]
e) What are
the possible outcome(s) expected from the following python code? Also specify
maximum and minimum value, which we can have. [2]
i) R - P - O
- R - ii) P - O - R - Y - iii) O -R - A
- G - iv) A- G - R - M -
2. a) What is
Object Oriented Programming? List some of its advantages. [2]
b) Consider the following class definition: [2]
marks=10
name= "ABC"
class Yourclass:
def __init__(self,marks,name):
self.marks=marks
self.name=name
def display(self):
print marks
print name
i)
Give the statement to create an
object of class Yourclass.
ii)
Assuming YC is the object, what
would be the output of YC.display()
c) Create the
class SOCIETY with following information: [4]
society_name,house_no,no_of_members,flat,income
Methods
An __init__
method to assign initial values of society_name as "Surya
Apartments", flat as "AType", house_no as 20, no_of_members as
3, income as 25000.
Inputdata( )
- to read data members(society,house_no,no_of_members&income) and call
allocate_flat().
allocate_flat(
) - To allocate flat according to income
Income Flat
>=25000 A Type
>=20000
and <25000 B Type
<15000 C Type
Showdata( ) -
to display the details of the entire class.
d) Give the statement to [2]
a. Check whether the attribute str exists in
the class Test whose object is T1
b. Assign a value "Hello" to the
attribute str of class Test and object T1.
e) Write the significance of statement 1 and write the type of
inheritance:
[2]
class person(object):
def__init__(self,name,age):
self.name=name
self.age=age
def display1(self):
print "Name :",self.name
print "Age :",self.age
class student(person):
def__init__(self,name,age,rollno,marks):
super(student,self).__init__(name,age)
self.rollno=rollno
self.marks=marks
def display(self):
self.display1()
print " Roll No:",self.rollno
print " Marks :",self.marks
class Gstudent(student):
def__init__(self,name,age,rollno,marks,stream):
super(Gstudent,self).__init__(name,age,rollno,marks) // Statement 1
self.stream=stream
def display2(self):
self.display()
print" stream:",self.stream
p=Gstudent('Mona',20,12,99,'computer')
p.display2 ()
3. a)Accept a list containing integers
randomly. Accept any number and display the position at which the number is
found is the list. [3]
b) Explain
try..except…else … with the help of user
defined function def divide(x, y)which
raises an error when the denominator is zero while dividing x by y and displays
the quotient otherwise. [3]
c)Write a program to input nXm matrix and find sum of all numbers using
function. [2]
d) Write a code snippet to generate squares using generator functions. [2]
e) Write the push operation of
stack containing names using class. [3]
f)Evaluate using stack 10, 3,*, 30,
2,*,- [2]
4. a) Explain seek()
method. [2]
b) Write
a program to accept a filename from the user and display all the lines from the
file which contain python comment character '#'. [2]
c) Consider a binary file
Employee.dat containing details such as
empno:ename:salary (separator ‘ :’). Write a python function to display
details of those employees who are earning between 25000 and 50000.(both values
inclusive) [3]
Marking Scheme
1. a) Set is unordered collection of values of any
type with no duplicate entry. It is immutable.
Dictionary is a mutable mapping
datatype. It consists of key: value pair.
Eg: L =[1,2,3,4,5] is a
list
D=
{1:”Ajay”,2:”Prashant,4:”Himani”} is a dictionary where 1,2,4 are keys and
“Ajay”,Prashant,”Himani” are their corresponding values.
[1 mark for any one point of dissimilarity] or [[2 mark for explanation using example]
b)
Ans: a. random b.re
[1/2 mark
each for writing the correct module names]
c)
Corrected Code:
class First():
def__init__(self):
print "first"
class Second(object):
def__init__(self):
print "second"
class Third(First,Second):
def__init__(self):
First.__init__(self)
Second.__init__(self)
print"Done"
t=Third()
Output:
first
second
Done
[ ½ mark each for
identifying and removing the colon
½ mark for each correct line of output]
d) Ans:The new string is: S1U3E5Ts
[1/2 mark
for each change i.e. S 1 3 E 5 s ]
e) True. Reason: f is of type None.
2. a) OOP allows decomposition of a problem into a
number of entities called objects and then builds data and functions around
these objects.
Advantages:
è
Simplicity
è
Modifiability
è
Extensibility
and Maintainability
è
Re-usability
è
Security
[ 1 mark for correct definition and 1
mark for any 2 advantages]
b) yc = Yourclass(marks,name)
Output:
10
ABC
[1
mark for declaring object with arguments
½
mark for each correct line of output]
c)
class SOCIETY:
# constructor to create an object
def__init__(self):
#constructor
self.society_name='Surya
Apartments'
self.house_no=20
self.no_of_members=3
self.flat='AType'
self.income=25000
def Inputdata(self):
self.society_name=raw_input("Enter Society Name")
self.house_no=input("Enter House Number")
self.no_of_members=input("Enter No. of members")
self.income=float(raw_input("Enter income"))
Allocate_Flat()
def Allocate_Flat(self):
if self.income>=25000:
self.flat='AType'
elif self.income>=20000
and self.income<25000:
self.flat='BType'
else:
self.flat='CType'
def Showdata(self):
print "Society Name",self.society_name
print "House_No",self.house_no
print "No.of members",self.no_of_members
print "Flat Type",self.flat
print "Income",self.income
S=SOCIETY()
S.Inputdata()
S.Showdata()
[ ½ mark for
correct declaration of
½ mark for init function
1 mark each
for Inputdata , Allocateflat and Showdata functions]
d) Ans.
a. hasattr (T1,str)
b. setattr (T1, str, “Hello”)
[ 1 mark for each correct answer]
e) Line 1:
super() function is used to call the methods of base class which
have been extended in derived class.Also
it is the importance of derived class __init__() to invoke the base class
__init__()
[1 mark for correct explanation
Type
of inheritance: multilevel
inheritance
[ 1 mark for the type of inheritance]
3. a)
maxrange=input("Enter Count
of numbers: ")
marks=[]
flag=False
for i in range(0,maxrange):
marks.append(input("?"))
number=input("Enter number
to be searched")
for i in range(0,maxrange):
if marks[i]==number:
print number,"found at position",i
flag=True
if flag==False:
print number,"not found in list"
[1
mark for correct for loop
1
mark for the condition
1
mark for printing both outputs]
b) def
divide(x, y):
try:
result = x /
y
except ZeroDivisionError:
print
"division by zero!"
else:
print "result is", result
In the above
example:
try block
consists of code that can raise an error.When
y(denominator) gets a 0 value,
ZeroDivisionError is raised which is handled by except clause.In case of no
exception else statement is executed.
In case there
is no error the statement(s) in else clause are executed . [1/2 mark for correct try block]
[1 mark for
handling zero division error using except clause]
[1/2 mark for
else clause]
[1 mark for
explanation]
c)
import random
import mataddition
m=input("Enter total
number of rows in the first matrix")
n=input("Enter total
number of columns in the first matrix")
a=[[random.random()forrowinrange(m)]forcolinrange(n)]
for i inrange(m):
for j
inrange(n):
a[i][j]=int(raw_input("?"))
s=mataddition.summat(a,m,n)
print s
[ 1 mark for getting the 2 matrices
1 mark for defining both for loops correctly
1 mark for sum]
d)
Ans.
# Squares using generator
def Square (n):
for i in range (n):
yield i**2
for k in Square (6):
print k,
[ 1
mark for defining the Square function with yield
1
mark for calling the Square function]
e)
class
stack:
s=[]
def push(self):
a=raw_input("Enter any name :")
stack.s.append(a)
def display(self):
l=len(stack.s)
for i inrange(l-1,-1,-1):
print stack.s[i]
a=stack()
n=input("Enter no. of
names")
for i in range(n):
a.push()
a.display()
[1 mark for declaring s
properly
1 mark for using append () function
1 mark for display ()
1 mark for calling the functions]
f)
[1 Mark each for any three operators operation using
stack]
[1 Mark for final result as -30]
4. a) The seek(offset[, from]) method
changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means
use the beginning of the file as the reference position and 1 means use the
current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position.
Example: f.seek (-3,2)
[1 mark for any correct explanation.
1 mark for example]
b)
try:
for line
in open("story.txt"):
line=line.strip()
if line[0]=='#':
print line
except:
print 'File Not Found'
[1 mark for opening and getting
lines from the file
1 mark for the comparison
½ mark for proper printing
½ mark for handling exceptions]
c)
Ans:
def Readfile():
i = open("Employee.dat","rb+")
x = i.readLine()
while(x):
I = x.split(':')
temp = float(I[2])
if (temp >=25000 and temp<=50000):
print x
x = i.readline()
[½ mark for opening “Employee.Dat” correctly.]
[½ mark for reading records from
Employee.Dat.]
[½ for iterating through the
file.]
[½ mark for using split().]
[½ mark for if statement to
check the condition.]
[½ for printing the relevant
record.]


