Python-programming-askbooks.net_ (1)
Python-programming-askbooks.net_ (1)
4 Sieve of Eratosthenes
and File I/O
CONTENTS
Part-1 : Sieve of Eratosthenes ................................ 4–2T to 4–4T
Sieve of Eratosthenes.
Questions-Answers
Answer
1. Sieve of Eratosthenes is a simple and ingenious ancient algorithm for
finding all prime numbers up to any given limit.
2. It does so by iteratively marking as composite (i.e., not prime) the
multiples of each prime, starting with the first prime number, 2.
3. The multiples of a given prime are generated as a sequence of numbers
starting from that prime, with constant difference between them that is
equal to that prime.
4. Following is the algorithm to find all the prime numbers less than or
equal to a given integer n by Eratosthenes’ method :
a. Create a list of consecutive integers from 2 to n : (2, 3, 4, …, n).
b. Initially, let p equal 2, the first prime number.
c. Starting from p2, count up in increments of p and mark each of
these numbers greater than or equal to p2 itself in the list. These
numbers will be p(p+1), p(p+2), p(p+3), etc.
d. Find the first number greater than p in the list that is not marked.
If there was no such number, stop. Otherwise, let p now equal this
number (which is the next prime), and repeat from step c.
Answer
1. Let us take an example when n = 50. So, we need to print all print
numbers smaller than or equal to 50.
2. We create a list of all numbers from 2 to 50.
2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
Python Programming 4–3 T (CC-Sem-3 & 4)
3. According to the algorithm we will mark all the numbers which are
divisible by 2 and are greater than or equal to the square of it.
2 3 4* 5 6* 7 8* 9 10*
11 12* 13 14* 15 16* 17 18* 19 20*
21 22* 23 24* 25 26* 27 28* 29 30*
31 32* 33 34* 35 36* 37 38* 39 40*
41 42* 43 44* 45 46* 47 48* 49 50*
4. Now we move to our next unmarked number 3 and mark all the numbers
which are multiples of 3 and are greater than or equal to the square of
it.
2 3 4* 5 6* 7 8* 9* 10*
11 12* 13 14* 15* 16* 17 18* 19 20*
21* 22* 23 24* 25 26* 27* 28* 29 30*
31 32* 33* 34* 35 36* 37 38* 39* 40*
41 42* 43 44* 45* 46* 47 48* 49 50*
5. We move to our next unmarked number 5 and mark all multiples of 5
and are greater than or equal to the square of it.
2 3 4* 5 6* 7 8* 9* 10*
11 12* 13 14* 15* 16* 17* 18* 19 20*
21* 22* 23 24* 25* 26* 27* 28* 29 30*
31 32* 33* 34* 35* 36* 37* 38* 39* 40*
41 42* 43 44* 45* 46* 47* 48* 49 50*
We continue this process and our final table will :
2 3 4* 5 6* 7 8* 9* 10*
11 12* 13 14* 15* 16* 17 18* 19 20*
21* 22* 23 24* 25* 26* 27* 28* 29 30*
31 32* 33* 34* 35* 36* 37 38* 39* 40*
41 42* 43 44* 45* 46* 47 48* 49* 50*
So the prime numbers are the unmarked ones : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47
Answer
def SieveOf Eratosthenes (n) :
# Create a boolean array “prime[0. . n]” and initialize
# all entries it as true. A value in prime[i] will
Sieve of Eratosthenes and File I/O 4–4 T (CC-Sem-3 & 4)
Questions-Answers
Answer
1. A file in a computer is a location for storing some related data.
2. It has a specific name.
3. The files are used to store data permanently on to a non-volatile memory
(such as hard disks).
4. As we know, the Random Access Memory (RAM) is a volatile memory
type because the data in it is lost when we turn off the computer. Hence,
we use files for storing of useful information or data for future reference.
Answer
1. Python has a built-in open () function to open files from the directory.
2. Two arguments that are mainly needed by the open () function are :
a. File name : It contains a string type value containing the name of
the file which we want to access.
b. Access_mode : The value of access_mode specifies the mode in
which we want to open the file, i.e., read, write, append etc.
3. Syntax :
file_object = open(file_name [, access_mode])
For example :
>>>f = open (“test.txt”) #Opening file current directory
>>>f = open (“C:/Python27/README.txt”)
#Specifying full path #Output
>>>f
<open file ‘C:/Python27/README.txt’, mode ‘r’ at 0x02BC5128>
#Output
Answer
1. When the operations that are to be performed on an opened file are
finished, we have to close the file in order to release the resources.
2. Python comes with a garbage collector responsible for cleaning up the
unreferenced objects from the memory, we must not rely on it to close
a file.
3. Proper closing of a file frees up the resources held with the file.
4. The closing of file is done with a built-in function close ().
5. Syntax :
fileObject. close ()
For example :
# open a file
>>> f = open (“test. txt”, “wb”)
# perform file operations
>>> f. close() # close the file
Answer
1. After opening a file, we have to perform some operations on the file.
Here we will perform the write operation.
2. In order to write into a file, we have to open it with w mode or a mode,
on any writing-enabling mode.
3. We should be careful when using the w mode because in this mode
overwriting persists in case the file already exists.
For example :
# open the file with w mode
>>> f = open (“C :/Python27/test.txt”, “w”)
# perform write operation
>>>f. write (‘writing to the file line 1/n’)
>>>f. write (‘writing to the file line 2/n’)
>>>f. write (‘writing to the file line 3/n’)
>>>f. write (‘writing to the file line 4’)
# clos the file after writing
>>> f.close ()
The given example creates a file named test.txt if it does not exist, and
overwrites into it if it exists. If we open the file, we will find the following
content in it.
Output :
Writing to the file line 1
Writing to the file line 2
Writing to the file line 3
Writing to the file line 4
Answer
1. In order to read from a file, we must open the file in the reading mode
(r mode).
2. We can use read (size) method to read the data specified by size.
3. If no size is provided, it will end up reading to the end of the file.
4. The read() method enables us to read the strings from an opened file.
5. Syntax :
file object. read ([size])
For example :
# open the file
Python Programming 4–7 T (CC-Sem-3 & 4)
Que 4.9. Discuss file I/O in Python. How to perform open, read,
write, and close into a file ? Write a Python program to read a file
line-by-line store it into a variable. AKTU 2019-20, Marks 10
Answer
File I/O : Refer Q. 4.4, Page 4–4T, Unit-4.
Open, read, write and close into a file : Refer Q. 4.5, Page 4–4T,
Refer Q. 4.8, Page 4–6T, Refer Q. 4.7, Page 4–5T, and Refer Q. 4.6,
Page 4–5T; Unit-4.
Program :
L = [“Quantum\n”, “for\n”, “Students\n”]
# writing to file
file1 = open(‘myfile.txt’, ‘w’)
file1.writelines(L)
file1.close()
# Using readlines()
file1 = open(‘myfile.txt’, ‘r’)
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
print(line.strip())
print(“Line{}: {}”.format(count, line.strip()))
Output :
Line1: Quantum
Line2: for
Line3: Students
Questions-Answers
Answer
1. An assertion is a sanity-check that we can turn on or turn off when we
are done with our testing of the program. An expression is tested, and if
the result is false, an exception is raised.
2. Assertions are carried out by the assert statement.
3. Programmers often place assertions at the start of a function to check
for valid input, and after a function call to check for valid output.
4. An AssertionError exception is raised if the condition evaluates to false.
5. The syntax for assert is : assert Expression [, Arguments]
6. If the assertion fails, Python uses ArgumentExpression as the argument
for the AssertionError.
For example :
Consider a function that converts a temperature from degrees Kelvin to
degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the
function fails if it sees a negative temperature :
#!/user/bip/python
def KelvinToFahrenheit(Temperature) :
assert (Temperature >= 0),“Colder than absolute zero!”
return ((Temperature – 273)*1.8) + 32
print KelvinToFahrenheit (273)
print int(KelvinToFahrenheit (505.78))
print KelvinToFahrenheit (– 5)
When the above code is executed, it produces the following result :
32.0
451
Traceback (most recent call last) :
File “test.py”, line 9, in<module>
print KelvinToFahrenheit (– 5)
File “test.py”, line 4, in KelvinToFahrenheit
assert (Temperature >= 0),“Colder than absolute zero!”
AssertionError : Colder than absolute zero!
Answer
1. While writing a program, we often end up making some errors. There
are many types of error that can occur in a program.
Python Programming 4–9 T (CC-Sem-3 & 4)
Answer
1. Whenever an exception occurs in Python, it stops the current process
and passes it to the calling process until it is handled.
2. If there is no piece of code in our program that can handle the exception,
then the program will crash.
3. For example, assume that a function X calls the function Y, which in
turn calls the function Z, and an exception occurs in Z. If this exception
is not handled in Z itself, then the exception is passed to Y and then to X.
If this exception is not handled, then an error message will be displayed
and our program will suddenly halt.
Sieve of Eratosthenes and File I/O 4–10 T (CC-Sem-3 & 4)
i. Try...except :
a. Python provides a try statement for handling exceptions.
b. An operation in the program that can cause the exception is
placed in the try clause while the block of code that handles
the exception is placed in the except clause.
c. The block of code for handling the exception is written by the
user and it is for him to decide which operation he wants to
perform after the exception has been identified.
Syntax :
try :
the operation which can cause exception here,
.........................
except Exceptionl1 :
if there is exception1, execute this.
except Exception2 :
if there is exception2, execute this.
.........................
else :
if no exception occurs, execute this.
ii. try finally :
a. The try statement in Python has optional finally clause that
can be associated with it.
b. The statements written in finally clause will always be executed
by the interpreter, whether the try statement raises an
exception or not.
c. With the try clause, we can use either except or finally, but not
both.
d. We cannot use the else clause along with a finally clause.
Answer
>>>try:
... file = open(“C:/Python27/test.txt”,“w”)
... file write(“hello python”)
... exceptIOError :
... print “Error: cannot find file or read data
... else :
... print “content written successfully”
>>> file. close ( )
Python Programming 4–11 T (CC-Sem-3 & 4)
1. In the given example, we are trying to open a file test.txt with write
access mode, and want to write to that file. We have added try and
except blocks.
2. If the required file is not found or we do not have the permission to write
to the file, an exception is raised.
3. The exception is handled by the except block and the following statement
printed :
Error : cannot find file or read data
4. On the other hand, if the data is written to the file then the else block
will be executed and it will print the following.
Output :
Content written successfully
Answer
>>> try :
... file = open(“testfile”,“w”)
... try :
... file.write(“Write this to the file”)
... finally :
... print “Closing file”
... file.close()
... exceptIOError:
print “Error Occurred”
1. In the given example, when an exception is raised by the statements of
try block, the execution is immediately passed to the finally block.
2. After all the statements inside the finally block are executed, the
exception is, raised again and is handled by the except block that is
associated with the next higher layer try block.
Answer
Exception : Refer Q. 4.11, Page 4–8T, Unit-4.
Assertions : Refer Q. 4.10, Page 4–8T, Unit-4.
Handle exceptions : Refer Q. 4.12, Page 4–9T, Unit-4.
Five built-in exceptions :
1. exception LookupError : This is the base class for those exceptions
that are raised when a key or index used on a mapping or sequence is
invalid or not found. The exceptions raised are :
a. KeyError
b. IndexError
Sieve of Eratosthenes and File I/O 4–12 T (CC-Sem-3 & 4)
For example :
try:
a = [1, 2, 3]
print a[3]
except LookupError :
print “Index out of bound error.”
else:
print “Success”
Output :
Index out of bound error.
2. TypeError : TypeError is thrown when an operation or function is
applied to an object of an inappropriate type.
For example :
>>> ‘2’+2
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in <module>
‘2’+2
TypeError: must be str, not int
3. exception ArithmeticError : This class is the base class for those
built-in exceptions that are raised for various arithmetic errors such
as :
a. OverflowError
b. ZeroDivisionError
c. FloatingPointError
For example :
>>> x=100/0
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
x=100/0
ZeroDivisionError: division by zero
4. exception AssertionError : An AssertionError is raised when an
assert statement fails.
For example :
assert False, ‘The assertion failed’
Output :
Traceback (most recent call last):
File “exceptions_AssertionError.py”, line 12, in
assert False, ‘The assertion failed’
AssertionError: The assertion failed
5. exception AttributeError :
An AttributeError is raised when an attribute reference or assignment
fails such as when a non-existent attribute is referenced.
For example :
class Attributes(object):
pass
object = Attributes()
print object.attribute
Python Programming 4–13 T (CC-Sem-3 & 4)
Output :
Traceback (most recent call last):
File “d912bae549a2b42953bc62da114ae7a7.py”, line 5, in
print object.attribute
AttributeError: ‘Attributes’ object has no attribute ‘attribute’
Questions-Answers
Answer
1. A module is a file containing Python definitions and statements. A module
can define functions, classes and variables.
2. It allows us to logically organize our Python code.
3. The file name is the module name with the suffix .py appended.
4. A module can also include runnable code. Grouping related code into a
module makes the code easier to understand and use.
5. Definitions from a module can be imported into other modules or into
the main module.
For example :
Here is an example of a simple module named as support.py
def print_func( par ):
print “Hello : ”, par
return
Que 4.17. Explain the import statement with the help of example.
Answer
1. The import statement is the most common way of invoking the import
machinery.
2. An import statement is made up of the import keyword along with the
name of the module.
3. The import statement combines two operations; it searches for the named
module, then it binds the results of that search to a name in the local
scope.
Sieve of Eratosthenes and File I/O 4–14 T (CC-Sem-3 & 4)
For example :
# to import standard module math
import math
print(“The value of pi is”, math.pi)
When we run the program, the output will be :
The value of pi is 3.141592653589793
Answer
1. Abstract Data type (ADT) is a type for objects whose behaviour is defined
by a set of value and a set of operations.
2. There are three types of ADTs :
a. List ADT : The data is stored in key sequence in a list which has a
head structure consisting of count, pointers and address of compare
function needed to compare the data in the list.
b. Stack ADT :
i. In stack ADT Implementation instead of data being stored in
each node, the pointer to data is stored.
ii. The program allocates memory for the data and address is
passed to the stack ADT.
iii. The head node and the data nodes are encapsulated in the
ADT.
iv. The calling function can only see the pointer to the stack.
v. The stack head structure also contains a pointer to top and
count of number of entries currently in stack.
c. Queue ADT :
i. The queue abstract data type (ADT) follows the basic design of
the stack abstract data type.
ii. Each node contains a void pointer to the data and the link
pointer to the next element in the queue.
iii. The program allocates the memory for storing the data.
Answer
1. ADT only defines as what operations are to be performed but not how
these operations will be implemented.
2. It does not specify how data will be organized in memory and what
algorithms will be used for implementing the operations.
3. It is called “abstract” because it gives an implementation-independent
view.
Python Programming 4–15 T (CC-Sem-3 & 4)
4. The process of providing only the essentials and hiding the details is
known as abstraction.
Public Private
Application Interface
Functions Functions
Program
Data Structures
Array Linked List
Memory
Fig. 4.19.1.
5. The user of data type does not need to know how that data type is
implemented, for example, we have been using primitive values like int,
float, char data types only with the knowledge that these data type can
operate and be performed on without any idea of how they are
implemented.
6. So, a user only needs to know what a data type can do, but not how it will
be implemented.
Que 4.20. Discuss ADT in Python. How to define ADT ? Write code
Answer
ADT in python : Refer Q. 4.18, Page 4–14T, Unit-4.
The Queue and Stack are used to define Abstract Data Types (ADT) in
Python.
Code for student information :
class Student :
# Constructor
def __init__(self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
# Function to create and append new student
def accept(self, Name, Rollno, marks1, marks2 ):
# use ‘int(input())’ method to take input from user
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
Sieve of Eratosthenes and File I/O 4–16 T (CC-Sem-3 & 4)
obj.display(ls[s])
elif(ch == 4):
obj.delete(2)
print(ls.__len__())
print(“List after deletion”)
for i in range(ls.__len__()):
obj.display(ls[i])
elif(ch == 5):
obj.update(3, 2)
print(ls.__len__())
print(“List after updation”)
for i in range(ls.__len__()):
obj.display(ls[i])
else:
print(“Thank You !”)
Questions-Answers
Answer
1. A class can be defined as a blue print or a previously defined structure
from which objects are made.
2. Classes are defined by the user; the class provides the basic structure
for an object.
3. It consists of data members and method members that are used by the
instances of the class.
4. In Python, a class is defined by a keyword Class.
5. Syntax : class class_name;
For example : Fruit is a class, and apple, mango and banana are its
objects. Attribute of these objects are color, taste, etc.
Sieve of Eratosthenes and File I/O 4–18 T (CC-Sem-3 & 4)
Answer
1. An object is an instance of a class that has some attributes and behaviour.
2. The object behaves according to the class of which it is an object.
3. Objects can be used to access the attributes of the class.
4. The syntax of creating an object in Python is similar to that for calling a
function.
5. Syntax :
obj_name = class_name ( )
For example :
s1 = Student ()
In the given example, Python will create an object s1 of the class student.
Answer
>>>class Student :
... ‘student details’
... def fill_details(self, name, branch, year):
... self.name = name
... self.branch = branch
... self.year = year
... print(“A Student detail object is created”)
... def print details (self) :
... print(‘Name: ’, self.name)
... print(‘Branch: ’,self.branch)
... print(‘Year: ’,self.year)
In the given example, we have created a class Student that contains two
methods: fill_details and print_details. The first method fill_details takes
four arguments: self, name, branch and year. The second method print_details
takes exactly one argument: self.
Answer
>>>class Student :
... ‘student details’
... def fill_details(self, name, branch, year):
... self.name = name
Python Programming 4–19 T (CC-Sem-3 & 4)
Answer
1. The __init__ function is a reserved function in classes in Python which
is automatically called whenever a new object of the class is instantiated.
2. As a regular function, the init function is also defined using the def
keyword. As per the object-oriented programming paradigm, these types
of functions are called constructors.
3. We use constructors to initialize variables.
4. We can pass any number of arguments while creating the class object as
per the definition of the init function.
Sieve of Eratosthenes and File I/O 4–20 T (CC-Sem-3 & 4)
For example :
class IntellipaatClass :
def__init__(self, course) :
self.course = course
def display(self) :
print(self.course)object1 = IntellipaatClass(“Python”)
object1.display( )
Output :
Python
4. In the above example, the init function behaves as a constructor and is
called automatically as soon as the ‘object1 = IntellipaatClass(“Python”)’
statement is executed.
5. Since it is a function inside a class, the first argument passed in it is the
object itself which is caught in the ‘self’ parameter.
6. The second parameter, i.e., course, is used to catch the second argument
passed through the object that is ‘Python’. And then, we have initialized
the variable course inside the init function.
7. Further, we have defined another function named ‘display’ to print the
value of the variable. This function is called using object1.
Answer
1. __str__method is the “informal” or nicely printable string representation
of an object. This is for the end user.
2. It is called by str(object) and the built-in functions such as format() and
print().
3. The return value of this method is a string object.
For example :
Class Account :
def __str__(self) :
return ‘Account of { } with starting amount : { }’ format
(self.owner, self.amount)
Now we can query the object in various ways and always get a nice
string representation :
>>> str(acc)
‘Account of bob with starting amount : 10’
Answer
1. The comparison methods are used whenever <, >, <=, >=, !=, == are
used with the object.
2. The comparison methods are also called ‘rich comparison methods’ or
‘comparison magic methods’.
3. Following are the comparison methods : _it_, _le_, _eq_, _ne_, _gt_,
_ge_.
object.__it__(self, other) # For x < y
object.__le__(self, other) # For x < = y
object.__eq__(self, other) # For x == y
object.__ne__(self, other) # For x ! = y OR x <> y
object.__gt__(self, other) # For x > y
object.__ge__(self, other) # For x > = Y
4. The most common usage is to return False or True when using one of
the comparison methods, but we can actually return any value.
5. If x == y it does not mean that x != y. The best practice is always to define
__ne__() if __eq__() is defined.
Answer
Method : Description
__add__(self, other) To get called on add operation using + operator
__sub__(self, other) To get called on subtraction operation using –
operator.
__mut__(self, other) To get called on multiplication operation using *
operator.
__floordiv__(self, To get called on floor division operation using //
other) operator.
__div__(self, other) To get called on division operation using /
operator.
For example :
class IntervalMath(object) :
def __init__(self, lower, upper) :
self. to = float (lower)
self. up = float (upper)
def __add__(self, other) :
Sieve of Eratosthenes and File I/O 4–22 T (CC-Sem-3 & 4)
Questions-Answers
Answer
1. The object-oriented programming approach mainly focuses on the object
and classes while procedural programming focuses on the function and
methods.
2. The object is an instance of class.
3. It is a collection of data (variables) and methods (functions).
4. A class can also be called the basic structure of object.
5. Class is set of attributes, which can be data members and methods
members.
Que 4.30.
4.10. Define the term inheritance.
Answer
1. A class ‘A’ that can use the characteristics of another class ‘B’ is said to be
a derived class, i.e., a class inherited from ‘B’. The process is called
inheritance.
2. In OOP, it means that reusability of code.
3. It is the capability of a class to derive the properties of another class that
has already been created.
For example : Vehicle is a class that is further divided into two
subclasses, automobiles (driven by motors) and pulled vehicles (driven
by men). Therefore, vehicle is the base class and automobiles and pulled
vehicles are its subclasses. These subclasses inherit some of the
properties of the base class vehicle.
Que 4.31. Give syntax of inheritance and explain with the help of
example.
Answer
Syntax :
Class sub_classname(Parent_classname):
‘Optional Docstring’
Class_suite
For example :
#Define a parent class Person
>>>class Person(object) :
‘returns a Person object with given name’
def get_name (self ,name) :
Sieve of Eratosthenes and File I/O 4–24 T (CC-Sem-3 & 4)
self.name = name
def get_details (self) :
‘returns a string containing name of person’
return self.name
#Define a subclass Student
>>>class Student (Person) :
‘return a Student object, takes 2 arguments’
def fill_details (self, name, branch) :
Person.get_name(self,name)
self.branch = branch
def get_details(self):
‘returns student details’
print(“Name:”, self.name)
print(“Branch: ”, self.branch)
#Define a subclass Teacher
>>>class Teacher(Person) :
‘returns a Teacher object, takes 1 arguments’
def fill_details(self, name, branch) :
Person.get_name(self,name)
def get_details(self) :
print(“Name:”, self.name)
#Define one object for each class
>>>person 1 = Person ()
>>>student 1 = Student ()
>>>teacher 1 = Teacher ()
#Fill details in the objects
>>> person1.get_name(‘John’)
>>> student1.fill_details(‘Jinnie’, ‘CSE’)
>>> teacher1.fill_details(‘Jack’)
#Print the details using parent class function
>>>print(personl.get_details())
John # Output
>>>print(studentl.get_details())
Name: Jinnie # Output
Branch: CSE # Output
>>>print(teacherl.get_details())
Python Programming 4–25 T (CC-Sem-3 & 4)
Answer
1. In multiple inheritance, a subclass is derived from more than one base
class.
2. The subclass inherits the properties of all the base classes.
3. In Fig. 4.32.1, subclass C inherits the properties of two base classes A
and B.
A B
4 Syntax :
# Define your first parent class
class A
...................... class_suite ..................
# Define your second parent class
class B
.......................class-suite......................
# Define the subclass inheriting both A and B
class C(A, B)
.......................class-suite......................
For example :
>>> class A : # Defining class A
def x(self):
print(“method of A”)
>>> class B : # Defining Class B
def x(self):
print(“method of B”)
>>> class C(A, B) : # Defining class C
pass
>>> y = c ()
>>> B.x(y)
Sieve of Eratosthenes and File I/O 4–26 T (CC-Sem-3 & 4)
method of B # Output
>>> A.x(Y)
method of A # Output.
Answer
1. Method overriding is allowed in Python.
2. Method overriding means that the method of parent class can be used in
the subclass with different or special functionality.
For example :
>>>class Parent :
def ovr_method (self) :
print ‘This is in Parent Class’
>>>class Child (Parent) :
def ovr_method (self) :
print ‘This is in Child Class’
>>>c = Child ()
>>>c.ovr_method()
This is in Child Class # Output
Answer
1. The word ‘Poly’ means ‘many’.
2. The term ‘polymorphism’ means that the object of a class can have many
different forms to respond in different ways to any message or action.
3. Polymorphism is the capability for a message or data to be processed in
one or more ways.
For example :
1. If a base class is mammals, then horse, human, and cat are its subclasses.
All the mammals can see in the daytime.
2. Therefore, if the message ‘see in the daytime’ is passed to mammals, all
the mammals including the human, the horse and the cat will respond
to it.
3. Whereas, if the message ‘see during the night time’ is passed to the
mammals, then only the cat will respond to the message as it can see
during the night as well as in daytime.
4. Hence, the cat, which is a mammal, can behave differently from the
other mammals.
Python Programming 4–27 T (CC-Sem-3 & 4)
Class shape
Draw ()
Answer
1. In Python programming language, encapsulation is a process to restrict
the access of data members. This means that the internal details of an
object may not be visible from outside of the object definition.
2. The members in a class can be assigned in three ways i.e., public,
protected and private.
3. If the name of a member is preceded by single underscore, it is assigned
as a protected member.
4. If the name of a member is preceded by double underscore, it is assigned
as a private member.
5. If the name is not preceded by anything then it is a public member.
Name Notation Behaviour
varname Public Can be accessed from anywhere
_varname Protected They are like the public members but they
cannot be directly accessed from outside
__varname Private They cannot be seen and accessed from outside
the class
For example :
>>>class MyClass (object) : #Defining class
def __init__ (self, x, y, z) :
self.var1 = x #public data member
self_var2 = y #projected data member
self__var3 = z #private data member
>>>obj = MyClass (3, 4, 5)
Sieve of Eratosthenes and File I/O 4–28 T (CC-Sem-3 & 4)
>>>obj.var1
3 #Output
>>>obj.var1 = 10
>>>obj.var1
10 #Output
>>>obj._var2
4 #Output
>>>obj._var2 = 12
>>>obj.var2
12 #Output
>>>obj.__var3 #Private member is not
accessible
Traceback (most recent call last) :
File “<pyshell#71>”, line 1, in<module>
obj.__var3
AttributeError : ‘MyClass’ object has no attribute ‘__var3’
Answer
1. In Python programming, there might be some cases when we intend to
hide the attributes of objects outside the class definition.
2. To accomplish this, use double score (__) before the name of the attributes
and these attributes will not be visible directly outside the class definition.
For example :
>>> class MyClass : # defining class
__ a = 0 ;
def sum (self, increment) :
self.__a += increment
self print.__ a
>>>b = MyClass() # creating instance of class
>>>b.sum(2)
2 #Output
>>> b.sum(5)
7 #Output
>>> print b. __a
Traceback (most recent call last) :
File “<pyshell#24>”, line 1, in <module>
print b.__a
Python Programming 4–29 T (CC-Sem-3 & 4)
Que 4.37. What will be the output after the following statements ?
class Furniture:
def legs():
print(‘is made of wood’)
Furniture.legs()
Answer
is made of wood
Que 4.38. What will be the output after the following statements ?
class Furniture:
def chair(x):
print(‘It has %s legs’ % x)
def table(x):
print(‘It has %s legs’ % x)
Furniture.table(6)
Answer
It has 6 legs
Que 4.39. What will be the output after the following statements ?
class Furniture:
def chair():
print(‘It has 4 legs’)
Sieve of Eratosthenes and File I/O 4–30 T (CC-Sem-3 & 4)
def table():
print(‘It has 6 legs’)
Furniture.chair()
Answer
It has 4 legs
Que 4.40. What will be the output after the following statements ?
import random
x = [3, 8, 6, 5, 0]
print(random.choice(x))
Answer
A random element from the list x.
Que 4.41. What will be the output after the following statements ?
import random
x = [3, 8, 6, 5, 0]
random.shuffle(x)
print(x)
Answer
The shuffled list x with the elements mixed up.
Que 4.42. What will be the output after the following statements ?
import re
x = re.compile(r‘(Sun)+day’)
y = x.search(‘Today is a nice day and a Sunday’)
print(y.group())
Answer
Sunday
Que 4.43. What will be the output after the following statements ?
import re
x = re.compile(r‘(Python){2}’)
y = x.search(‘PythonPythonPython’)
print(y.group())
Answer
PythonPython
Que 4.44. What will be the output after the following statements ?
import re
x = re.compile(r‘(Python){2,3}’)
Python Programming 4–31 T (CC-Sem-3 & 4)
y = x.search(‘PythonPythonPython’)
print(y.group())
Answer
PythonPythonPython
Que 4.45. What will be the output after the following statements ?
import re
x = re.compile(r‘(Python){1,3}?’)
y = x.search(‘PythonPythonPython’)
print(y.group())
Answer
Python
Que 4.46. What will be the output after the following statements ?
import re
x = re.compile(r‘day’)
y = x.findall(‘Today is a nice day and a Sunday’)
print(y)
Answer
[‘day’, ‘day’, ‘day’]
Que 4.47. What will be the output after the following statements ?
import re
x = re.compile(r‘(Sun)?day’)
y = x.findall(‘Today is a nice day and a Sunday’)
print(y)
Answer
[‘ ’, ‘ ’, ‘Sun’]
Que 4.48. What will be the output after the following statements ?
import os
x = os.getcwd()
print(x)
Answer
The current working directory
Que 4.49. What do the following statements do ?
import webbrowser
webbrowser.open(‘http://google.com’)
Sieve of Eratosthenes and File I/O 4–32 T (CC-Sem-3 & 4)
Answer
Launch a browser window to http://google.com
Que 4.50.
4.10. What will be the output after the following statements ?
import sys
print(sys.argv)
Answer
A list of the program’s filename and command line arguments
Python Programming 5–1 T (CC-Sem-3 & 4)
5 Iterators and
Recursion
CONTENTS
Part-1 : Iterators and Recursion : .......................... 5–2T to 5–7T
Recursive Fibonacci,
Tower of Hanoi
Questions-Answers
Answer
1. An iterator is an object that contains a countable number of values.
2. An iterator is an object that can be iterated upon, meaning that we can
traverse through all the values.
3. Python iterator, implicitly implemented in constructs like for-loops,
comprehensions, and python generators.
4. Python lists, tuples, dictionary and sets are all examples of in-built
iterators.
5. These types are iterators because they implement following methods :
a. __iter__ : This method is called on initialization of an iterator. This
should return an object that has a next() method.
b. next() (or __next__) : The iterator next method should return the
next value for the iterable. When an iterator is used with a ‘for in’
loop, the for loop implicitly calls next() on the iterator object. This
method should raise a StopIteration to signal the end of the iteration.
For example :
# An iterable user defined type
class Test:
# Constructor
def __init__(self, limit):
self.limit = limit
# Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element.
def next(self):
# Store current value of x
x = self.x
Python Programming 5–3 T (CC-Sem-3 & 4)
Answer
1. In Python, recursion occurs when a function is defined by itself.
2. When a function calls itself, directly or indirectly, then it is called a
recursive function and this phenomenon is known as recursion.
3. Recursion is the property how we write a function. A function which
performs the same task can be written either in a recursive form or in
an iterative form.
4. Recursion is the process of repeating something self-similar way.
For example :
def fact (n) :
if n == 0:
return 1
else :
return n * fact(n – 1)
print(fact(0))
print(fact(5))
Output :
1
120
Answer
1. Fibonacci series is a series of numbers formed by the addition of the
preceding two numbers in the series.
2. It is simply the series of numbers which starts from 0 and 1 and then
continued by the addition of the preceding two numbers.
3. Example of Fibonacci series: 0, 1, 1, 2, 3, 5.
4. Python code for recursive Fibonacci :
def FibRecursion(n) :
if n <= 1 :
return n
else :
return(FibRecursion(n – 1) + FibRecursion(n – 2))
nterms = int(input(“Enter the term : ”)) # take input from the user
if nterms < = 0: # check if the number is valid
print (“Please enter a positive integer”)
else :
print (“Fibonacci sequence :”)
for i in range (nterms) :
print(FibRecursion(i))
Output : Enter the term : 5
Fibonacci sequence :
01123
1. In the given Python program, we use recursion to generate the Fibonacci
sequence.
2. The function FibRecursion is called recursively until we get the output.
3. In the function, we first check if the number n is zero or one. If yes, it
returns the value of n. If not, we recursively call FibRecursion with the
values n – 1 and n – 2.
Answer
Iterator : Refer Q. 5.1, Page 5–2T, Unit-5.
Tower of Hanoi problem :
1. Tower of Hanoi is a mathematical puzzle which consists of three rods
and a number of disks of different sizes, which can slide onto any rod.
2. The puzzle starts with the disks in a neat stack in ascending order of size
on one rod, the smallest at the top, thus making a conical shape.
Python Programming 5–5 T (CC-Sem-3 & 4)
3. The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules :
a. Only one disk can be moved at a time.
b. Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack.
c. A disk can only be moved if it is the uppermost disk on a stack.
d. No disk may be placed on top of a smaller disk.
3 Disk 1
A B C A B C
2 3 4
A B C A B C A B C
5 6 7
A B C A B C A B C
Fig. 5.4.1.
Answer
Questions-Answers
Que 5.6. What is simple (linear) search ? Explain with the help of
example.
Answer
1. Linear search is a method for finding a particular value in a list.
2. Linear search is good to use when we need to find the first occurrence
of an item in an unsorted collection.
3. Linear (Simple) search is one of the simplest searching algorithms, and
the easiest to understand.
4. It starts searching the value from the beginning of the list and continues
till the end of the list until the value is found.
5. Code :
def seach(arr, n, x) :
i=0
for i in range(i, n) :
if (arr[i] == x) :
return – i
return – 1
For example :
arr = [3, 10, 30, 45]
x = 10
n = len(arr)
print(x, “is present at index”, search(arr, n, x))
Output : 10 is present at index 1
Answer
1. Let T(n) denote the time taken by a search on a sequence of size n.
2. Therefore, recurrence relation is : T(n) = T(n – 1) + C
3. Solution to the recurrence relation is: T(n)= Cn
4. We have three cases to analyse an algorithm:
a. Worst case :
i. In the worst case analysis, we calculate upper bound on running
time of an algorithm.
ii. For linear search, the worst case happens when the element
to be searched is not present in the array.
iii. When x is not present, the search() functions compares it with
all the elements of arr[] one by one.
iv. Therefore, the worst case time complexity of linear search
would be (n).
b. Average case :
i. In average case analysis, we take all possible inputs and calculate
computing time for all of the inputs.
ii. For the linear search problem, let us assume that all cases are
uniformly distributed (including the case of x not being present
in array). So, we sum all the cases and divide the sum by
(n + 1).
iii. Therefore, the average case time complexity of linear search
would be (n).
c. Best case :
i. In the best case analysis, we calculate lower bound on running
time of an algorithm.
ii. In the linear search problem, the best case occurs when x is
present at the first location.
iii. So, time complexity in the best case would be (1).
Answer
1. Binary search follows a divide and conquer approach. It is faster than
linear search but requires that the array be sorted before the algorithm
is executed.
2. Binary search looks for a particular item by comparing the middle most
item of the collection. If a match occurs, then the index of item is returned.
3. If the middle item is greater than the item, then the item is searched in
the sub-array to the left of the middle item.
Python Programming 5–9 T (CC-Sem-3 & 4)
4. Otherwise, the item is searched for in the sub-array to the right of the
middle item.
5. This process continues on the sub-array as well until the size of the
sub-array reduces to zero.
6. Code :
def binarysearch(arr, 1, r, x) :
while 1 <= r :
mid = 1 + (r – 1)/2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x :
l = mid + 1
# If x is smaller, ignore right half
else :
r = mid – 1
# If we reach here, then the element was not present
return – 1
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr) – 1, x)
if result ! = – 1:
print “Element is present at index % d” % result
else :
print “Element is not present in array”
Output :
Element is present at index 3
Answer
1. Let T(n) denote the time taken by a search on a sequence of size n.
2. Therefore, recurrence relation is : T(n) <= T(n/2) + C
3. Solution to the recurrence relation is : T(n) = log(n)
Iterators and Recursion 5–10 T (CC-Sem-3 & 4)
Questions-Answers
Answer
1. The selection sort algorithm sorts an array by repeatedly finding the
smallest element (considering ascending order) from unsorted list and
swapping it with the first element of the list.
2. The algorithm maintains two sub-arrays in a given array:
i. The sub-array which is already sorted.
ii. Remaining sub-array which is unsorted.
3. In every iteration of selection sort, the smallest element from the
unsorted sub-array is picked and moved to the sorted sub-array.
4. Code :
def slectionSort(nlist) :
for fillslot in range(len(nlist) – 1, 0, – 1) :
maxpos = 0
for location in range(1, fillslot + 1) :
if nlist[location]>nlist[maxpos] :
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
selectionSort(nlist)
print(nlist)
Output :
[14, 21, 27, 41, 43, 45, 46, 57, 70]
5. Time complexity :
i. Best case : O(n2)
ii. Worst case : O(n2)
iii. Average case : O(n2)
Answer
1. Merging is defined as the process of creating a sorted list/array of data
items from two other sorted array/list of data items.
2. Merge list means to merge two sorted list into one list.
Code for merging two lists and sort it :
a=[ ]
c=[ ]
Iterators and Recursion 5–12 T (CC-Sem-3 & 4)
Answer
1. Merge sort is a divide and conquer algorithm. It divides input array in
two halves, calls itself for the two halves and then merges the two
sorted halves.
2. The merge() function is used for merging two halves.
3. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m + 1 ..r] are sorted and merges the two sorted sub-arrays into one.
4. Code :
def mergeSort(arr)
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i=j=k=0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else :
arr[k] = R[j]
Python Programming 5–13 T (CC-Sem-3 & 4)
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i],end=“ ”)
print()
# driver code to test the above code
if __name__ == ‘__main__ ’ :
arr = [12, 11, 13, 5, 6, 7 ]
print (“Given array is”, end = “\n”)
printList(arr)
mergeSort(arr)
print(“Sorted array is: ”, end = “\n”)
printList(arr)
Output :
Given array is
12, 11, 13, 5, 6, 7
Sorted array is
5, 6, 7, 11, 12, 13
5. Time complexity : Recurrence relation of merge sort is given by
T(n) = 2T(n/2) + Cn
= 2(2T(n/4) + Cn/2) + Cn = 22T(n/4) + 2Cn
= 22(2T(n/8) + Cn/4) + Cn = 23T(n/8) + 3Cn
= ... // keep going for k steps
= 2kT(n/2k) + k*Cn
Iterators and Recursion 5–14 T (CC-Sem-3 & 4)
Answer
1. Python also supports higher order functions, meaning that functions
can accept other functions as arguments and return functions to the
caller.
2. Sorting of higher order functions :
a. In order to defined non-default sorting in Python, both the sorted()
function and .sort() method accept a key argument.
b. The value passed to this argument needs to be a function object
that returns the sorting key for any item in the list or iterable.
3. For example : Consider the given list of tuples, Python will sort by
default on the first value in each tuple. In order to sort on a different
element from each tuple, a function can be passed that return that
element.
>>> def second_element (t) :
... return t[1]
...
>>> zepp = [(‘Guitar’, ‘Jimmy’), (‘Vocals’, ‘Robert’), (‘Bass’, ‘John Paul’),
(‘Drums’, ‘John’)]
>>> sorted(zepp)
[(‘Bass’, ‘John Paul’), (‘Drums’, ‘John’), (‘Guitar’, ‘Jimmy’), (‘Vocals’,
‘Robert’)]
>>> sorted(zepp, key = second_element)
[(‘Guitar’, ‘Jimmy’), (‘Drums’, ‘John’), (‘Bass’, ‘John Paul’), (‘Vocals’,
‘Robert’)]
Answer
Python Programming 5–15 T (CC-Sem-3 & 4)
Sorting :
1. Sorting refers to arranging data in a particular order.
2. Most common orders are in numerical or lexicographical order.
3. The importance of sorting lies in the fact that data searching can be
optimized to a very high level, if data is stored in a sorted manner.
4. Sorting is also used to represent data in more readable formats.
Merging : Refer 5.11, Page 5–11T, Unit-5.
Different types of sorting are :
1. Bubble sort : It is a comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they
are not in order.
For example :
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list) – 1,0, – 1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
Output :
[2, 6, 11, 19, 27, 31, 45, 121]
2. Merge sort : Refer 5.12, Page 5–12T, Unit-5.
3. Selection sort : Refer 5.10, Page 5–10T, Unit-5.
4. Higher order sort : Refer 5.13, Page 5–14T, Unit-5.
5. Insertion sort :
a. Insertion sort involves finding the right place for a given element
in a sorted list. So in beginning we compare the first two elements
and sort them by comparing them.
b. Then we pick the third element and find its proper position among
the previous two sorted elements.
c. This way we gradually go on adding more elements to the already
sorted list by putting them in their proper position.
Iterators and Recursion 5–16 T (CC-Sem-3 & 4)
For example :
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j=i–1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j – 1
InputList[j+1] = nxt_element
list = [19,2,30,42,28,11,135,26]
insertion_sort(list)
print(list)
Output :
[2, 11, 19, 26, 28, 30, 42, 135]
Program : Refer Q. 4.3, Page 4–3T, Unit-4.
Answer
[11, 14, 25, 53, 62]
Answer
[‘15’, ‘25’, ‘53’, ‘Sunday’, ‘Today’]
Que 5.17. What will be the output after the following
statements ?
x = {5:4, 8:8, 3:16, 9:32}
print(sorted(x.items()))
Python Programming 5–17 T (CC-Sem-3 & 4)
Answer
[(3, 16), (5, 4), (8, 8), (9, 32)]
Que 5.18. What will be the output after the following
statements ?
x = [‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’]
x.sort()
print(x)
Answer
[‘A’, ‘B’, ‘C’, ‘a’, ‘b’, ‘c’]
Answer
[‘a’, ‘A’, ‘b’, ‘B’, ‘c’, ‘C’]
Answer
[‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’]
Answer
TypeError
Que 5.22. What will be the data type of the output after the
following statements ?
x = ‘Python’
y = list(x)
print(y)
Iterators and Recursion 5–18 T (CC-Sem-3 & 4)
Answer
List
Que 5.23. What will be the data type of the output after the
following statements ?
x = ‘Python’
y = tuple(x)
print(y)
Answer
Tuple
Python Programming SQ–1 T (CC-Sem-3 & 4)
1 Introduction and
Basics
(2 Marks Questions)
Ans.
S. No. Arrays Lists
1. Arrays can only store Lists can store heterogeneous
homogeneous data (data of and arbitrary data.
the same type).
2. Arrays use less memory to Lists require more memory to
store data. store data.
3. The length of an array is The length of a list is not fixed,
pre-fixed while creating it, so so more elements can be added.
more elements cannot be
added.
Ans. Floor division returns the quotient in which the digits after the
decimal point are removed. But if one of the operands (dividend
and divisor) is negative, then the result is floored, i.e., rounded
away from zero (means, towards the negative of infinity). It is
denoted by “//”.
For example :
5.0 // 2
2.0
1.26. Name the tools that are used for static analysis.
Ans.
1. Pychecker
2. Pylint
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Python Programming SQ–7 T (CC-Sem-3 & 4)
2 Marks Questions SQ–10 T (CC-Sem-3 & 4)
Ans. Python also allows users to define their own functions. To use their
own functions in Python, users have to define the functions first;
this is known as function definition. In a function definition, users
have to define a name for the new function and also the list of the
statements that will execute when the function will be called.
Syntax :
def functionname (parameters) :
“function_docstring”
statement (s)
return (expression)
3.13. You have been given a string ‘I live in Cochin. I love pets.’
Divide this string in such a very that the two sentences in
it are separated and stored in different variables. Print them.
Ans. >>> var = ‘I live in Cochin, I love pets.’
>>> var1 = var[: 17]
>>> var2 = var[18 : 30]
>>> print var1
I live in Cochin, # Output
>>> print var2
I love pets, # Output
3.18. Give examples for all, any, len and sorted methods in
dictionary.
Ans. >>> dict1 = {8 : ‘a’, 3 : ‘b’, 5 : ‘c’, 7 : ‘d’}
>>> all (dict1)
True # Output
>>> any(dict1)
True # Output
>>> len (dict1)
4 # Output
>>> sorted(dict1)
[3, 5, 7, 8] # Output
>>>float (5.50)
5 # Output
3.22. What are the types of arguments used for calling a function ?
Ans. Four types of arguments used for calling a function :
i. Required argument
ii. Keyword argument
iii. Default argument
iv. Variable length argument
3.23. Give one-one example for zip, max and min methods.
Ans. >>> tuple1 = (‘a’, ‘b’, ‘c’)
>>> tuple1 = (1, 2, 3)
>>> max (tuple 2)
3 # Output
>>>min(tuple 1)
‘a’ # Output
>>>zip(tuple 1, tuple 2)
{(‘a’, 1), (‘b’, 2), (‘c’, 3)} # Output
3.23. What is the output of print list[2] when list = [‘abcd’, 2.23,
‘john’] ?
Python Programming SQ–15 T (CC-Sem-3 & 4)
Ans. john
2 Marks Questions SQ–16 T (CC-Sem-3 & 4)
4 Sieve of Eratosthenes
and File I/O
(2 Marks Questions)
4.16. Give the syntax for reading from a file. What is the work of
the readline() function ?
Ans. Syntax :
fileobject.read([size])
The count parameter size gives the number of bytes to be read
from an opened file. It starts reading from the beginning of the file
until the size given. If no size is provided, it ends up reading until
the end of the file.
2 Marks Questions SQ–20 T (CC-Sem-3 & 4)
5 Iterators and
Recursion
(2 Marks Questions)
Drawbacks :
1. Its drawback is that if our list is large, it may take time to go
through the list.
2. In the worst-case scenario, the item we are searching for may not
be in the list, or it may be at the opposite end of the list.
Ans.
1. Insertion sort
2. Selection sort
3. Bubble sort
4. Merge sort
Python Programming SP–1 T (CC-Sem-3 & 4)
B.Tech.
(SEM. III) ODD SEMESTER THEORY
EXAMINATION, 2019-20
PYTHON PROGRAMMING
Time : 3 Hours Max. Marks : 100
Section-B
Section-C
Solved Paper (2019-20) SP–4 T (CC-Sem-3 & 4)
Ans.
i. Global variables :
1. Global variables are the variables that are defined outside a
function body.
2. Global variables can be accessed throughout the program body
by all functions.
ii. Local variables :
1. Local variables are the variables that are defined inside a
function body.
2. Local variables can be accessed only inside the function in
which they are declared.
3. When we call a function, the variables declared inside it are
brought into scope.
Section-B
Output :
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
For example :
Keyword if (x > y) :
return x
else 2 arguments
Function name return y x and y
(formal args)
a = max(8, 6)
Body of the function
Documentation comment
Call to the function. (docstring).
Actual args are 8 and 6.
Fig. 2.
1. Keyword : The keyword ‘def’ is used to define a function header.
2. Function name : We define the function name for identification
or to uniquely identify the function. In the given example, the
function name is max. Function naming follows the same rules of
writing identifiers in Python.
3. A colon (:) to mark the end of function header.
4. Arguments : Arguments are the values passed to the functions
between parentheses. In the given example, two arguments are
used, x and y. These are called formal arguments.
5. Body of the function : The body processes the arguments to do
something useful. In the given example, body of the function is
intended w.r.t. the def keyword.
6. Documentation comment (docstring) : A documentation string
(docstring) to describe what the function does. In the given example,
“return maximum among x and y” is the docstring.
7. An optional return statement to return a value from the function.
8. Function call : To execute a function, we have to call it. In the
given example, a = max (8, 6) is calling function with 8 and 6 as
arguments.
Scope :
1. Scope of a name is the part of the program in which the name can
be used.
Python Programming SP–9 T (CC-Sem-3 & 4)
2. Two variables can have the same name only if they are declared in
separate scopes.
3. A variable cannot be used outside its scopes.
4. Fig. 3 illustrates Python’s four scopes.
Built-in (Python)
Names preassigned in the built-in names module: open, range,
SyntaxError....
Global (module)
Names assigned at the top-level of module file, or declared
global in a def within the file.
Enclosing function locals
Names in the local scope of any and all enclosing functions
(def or lambda), from inner to outer.
Local (function)
Names assigned in any way within a function
(def or lambda), and not declared global in that function.
return x * y
# This function divides two numbers
def divide(x, y) :
return x / y
print(“Select operation.”)
print(“1.Add”)
print(“2.Subtract”)
print(“3.Multiply”)
print(“4.Divide”)
# Take input from the user
choice = input(“Enter choice(1/2/3/4) : ”)
num1 = float(input(“Enter first number: ”))
num2 = float(input(“Enter second number: ”))
if choice == ‘1’ :
print(num1,“+”,num2,“=”, add(num1,num2))
elif choice == ‘2’ :
print(num1,“–”,num2,“=”, subtract(num1,num2))
elif choice == ‘3’ :
print(num1,“*”,num2,“=”, multiply(num1,num2))
elif choice == ‘4’:
print(num1,“/”,num2,“=”, divide(num1,num2))
else :
print(“Invalid input”)
c. Queue ADT :
i. The queue abstract data type (ADT) follows the basic
design of the stack abstract data type.
ii. Each node contains a void pointer to the data and the link
pointer to the next element in the queue.
iii. The program allocates the memory for storing the data.
The Queue and Stack are used to define Abstract Data Types
(ADT) in Python.
Code for student information :
class Student :
# Constructor
def __init__(self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
# Function to create and append new student
def accept(self, Name, Rollno, marks1, marks2 ):
# use ‘int(input())’ method to take input from user
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
# Function to display student details
def display(self, ob):
print(“Name :”, ob.name)
print(“RollNo :”, ob.rollno)
print(“Marks1 :”, ob.m1)
print(“Marks2 :”, ob.m2)
print(“\n”)
# Search Function
def search(self, rn):
for i in range(ls.__len__()):
if(ls[i].rollno == rn):
return i
# Delete Function
def delete(self, rn):
i = obj.search(rn)
del ls[i]
# Update Function
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
Solved Paper (2019-20) SP–12 T (CC-Sem-3 & 4)
Section-C
List :
1. A list can contain the same type of items.
2. Alternatively, a list can also contain different types of items.
3. A list is an ordered and indexable sequence.
4. To declare a list in Python, we need to separate the items using
commas and enclose them within square brackets ([ ]).
5. Operations such as concatenation, repetition and sub-list are done
on list using plus (+), asterisk (*) and slicing (:) operator.
For example :
>>>first = [1, “two”, 3.0, “four” ] # 1st list
>>>second = [“five”, 6] # 2nd list
>>>first # display 1st list
[1, ‘two’, 3.0, ‘four’] # Output
Tuple :
1. A tuple is also used to store sequence of items.
2. Like a list, a tuple consists of items separated by commas.
3. Tuples are enclosed within parentheses rather than within square
brackets.
For example :
>>>third = (7, “eight”, 9, 10.0)
>>>third
(7, ‘eight’, 9, 10.0) # Output
Dictionary :
1. A Python dictionary is an unordered collection of key-value pairs.
2. When we have the large amount of data, the dictionary data type
is used.
3. Keys and values can be of any type in a dictionary.
4. Items in dictionary are enclosed in the curly-braces {} and separated
by the comma (,).
5. A colon (:) is used to separate key from value. A key inside the
square bracket [ ] is used for accessing the dictionary items.
For example :
>>> dict1 = {1:“first line”, “second” : 2} # declare dictionary
>>> dict1[3] = “third line” # add new item
>>> dict1 # display dictionary
{1 : ‘first line’, ‘second’ : 2, 3: ‘third line’} # Output
Boolean :
1. In a programming language, mostly data is stored in the form of
alphanumeric but sometimes we need to store the data in the
form of ‘Yes’ or ‘No’.
Python Programming SP–19 T (CC-Sem-3 & 4)
Test False
condition
?
True
Execute
Loop
Out of Loop
Fig. 8.
a. In the flow chart if the test condition is true, then the loop is
executed, and if it is false then the execution breaks out of the
loop.
b. After the loop is successfully executed the execution again
starts from the loop entry and again checks for the test
condition, and this keeps on repeating until the condition is
false.
Break statement :
1. The break keyword terminates the loop and transfers the control
to the end of the loop.
2. While loops, for loops can also be prematurely terminated using the
break statement.
3. The break statement exits from the loop and transfers the execution
from the loop to the statement that is immediately following the
loop.
For example :
>>> count = 2
>>> while True :
print count
count = count + 2
if count > = 12 :
break # breaks the loop
Output :
2
4
Solved Paper (2019-20) SP–26 T (CC-Sem-3 & 4)
6
8
10
Continue statement :
1. The continue statement causes execution to immediately continue
at the start of the loop, it skips the execution of the remaining body
part of the loop.
2. The continue keyword terminates the ongoing iteration and
transfers the control to the top of the loop and the loop condition is
evaluated again. If the condition is true, then the next iteration
takes place.
3. Just as with while loops, the continue statement can also be used in
Python for loops.
For example :
>>> for i in range (1, 10) :
if i % 2! = 0 :
continue # if condition becomes true, it skips the print part
print i
Output :
2
4
6
8
Program to convert time format :
# Function to convert the time format
def convert24(str1):
# Checking if last two elements of time # is AM and first two
elements are 12
if str1[– 2:] == “AM” and str1[:2] == “12”:
return “00” + str1[2:– 2]
# remove the AM
elif str1[-2:] == “AM”:
return str1[:– 2]
# Checking if last two elements of time is PM and first two elements
are 12
elif str1[– 2:] == “PM” and str1[:2] == “12”:
return str1[:– 2]
else:
# add 12 to hours and remove PM
return str(int(str1[:2]) + 12) + str1[2:8]
# Driver Code
print(convert24(“08:05:45 PM”))
Python Programming SP–27 T (CC-Sem-3 & 4)
Here the results of previous two elements are added to the next
e leme nt and this go e s o n till the e nd of the list like
(((((5+8)+10)+20)+50)+100).
Program to count occurrences of an element in a list :
# vowels list
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]
# count element ‘i’
count = vowels.count(‘i’)
# print count
print(‘The count of i is:’, count)
# count element ‘p’
count = vowels.count(‘p’)
# print count
print(‘The count of p is:’, count)
Output :
The count of i is: 2
The count of p is: 0
>>> roll
27
>>> regdcourse
(‘Python’, ‘Abha’, 303)
B. Mutable sequences :
1. Python represents all its data as objects. Mutability of object is
determined by its type.
2. Some of these objects like lists and dictionaries are mutable,
meaning we can change their content without changing their
identity.
3. Other objects like integers, floats, strings and tuples are
immutable, meaning we cannot change their contents.
4. Dictionaries are mutable in Python :
a. Dictionaries in Python are mutable.
b. The values in a dictionary can be changed, added or deleted.
c. If the key is present in the dictionary, then the associated
value with that key is updated or changed; otherwise a
new key : value pair is added.
For example :
>>> dict1 = {‘name’ : ‘Akash’, ‘age’ : 27}
>>> dict1[‘age’] = 30 # updating a value
>>> print dict
{‘age’ : 30, ‘name’: ‘Akash’} # Output
>>> dict1[‘address’] = ‘Alaska’ # adding a key : value
>>>print dict1
{‘age’: 30, ‘name’: ‘Akash’, ‘address’: ‘Alaska’} # Output
In the given example, we tried to reassign the value ‘30’ to the
key ‘age’, Python interpreter first searches the key in the
dictionary and then update it. Hence, the value of ‘age’ is updated
to 30. However, in the next statement, it does not find the key
‘address’; hence, the key: value ‘address’ : ‘Alaska’ is added to
the dictionary.
C. List comprehension :
1. List comprehension is used to create a new list from existing
sequences.
2. It is a tool for transforming a given list into another list.
3. Using list comprehension, we can replace the loop with a single
expression that produces the same result.
4. The syntax of list comprehension is based on set builder notation
in mathematics.
Solved Paper (2019-20) SP–30 T (CC-Sem-3 & 4)
>>> List1 = [10, 20, 30, 40, 50] >>> List1 = [10, 20, 30, 40, 50]
>>> List1 >>> List1= [x + 10 for x in List1]
[10, 20, 30, 40, 50] >>> List1
>>> for i in range (0, len(List1)) : [20, 30, 40, 50, 60]
List1 [i] = List1[i] + 10
>>> List1
[20, 30, 40, 50, 60]
Without list comprehension Using list comprehension
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
print(line.strip())
print(“Line{}: {}”.format(count, line.strip()))
Output :
Line1: Quantum
Line2: for
Line3: Students
For example :
>>> ‘2’+2
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in <module>
‘2’+2
TypeError: must be str, not int
3. exception ArithmeticError : This class is the base class for
those built-in exceptions that are raised for various arithmetic
errors such as :
a. OverflowError
b. ZeroDivisionError
c. FloatingPointError
For example :
>>> x=100/0
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
x=100/0
ZeroDivisionError: division by zero
4. exception AssertionError : An AssertionError is raised when
an assert statement fails.
For example :
assert False, ‘The assertion failed’
5. exception AttributeError :
An AttributeError is raised when an attribute reference or
assignment fails such as when a non-existent attribute is
referenced.
For example :
class Attributes(object):
pass
object = Attributes()
print object.attribute
Ans.
Property Recursion Iteration
4. Code :
def mergeSort(arr)
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i=j=k=0
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i],end=“ ”)
print()
# driver code to test the above code
if __name__ == ‘__main__ ’ :
arr = [12, 11, 13, 5, 6, 7 ]
print (“Given array is”, end = “\n”)
printList(arr)
mergeSort(arr)
print(“Sorted array is: ”, end = “\n”)
printList(arr)
3. Selection sort :
1. The selection sort algorithm sorts an array by repeatedly finding
the smallest element (considering ascending order) from
unsorted list and swapping it with the first element of the list.
2. The algorithm maintains two sub-arrays in a given array:
i. The sub-array which is already sorted.
ii. Remaining sub-array which is unsorted.
3. In every iteration of selection sort, the smallest element from
the unsorted sub-array is picked and moved to the sorted sub-
array.
4. Code :
def slectionSort(nlist) :
for fillslot in range(len(nlist) – 1, 0, – 1) :
maxpos = 0
for location in range(1, fillslot + 1) :
Python Programming SP–39 T (CC-Sem-3 & 4)
if nlist[location]>nlist[maxpos] :
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
selectionSort(nlist)
print(nlist)
4. Higher order sort :
1. Python also supports higher order functions, meaning that
functions can accept other functions as arguments and return
functions to the caller.
2. Sorting of higher order functions :
a. In order to defined non-default sorting in Python, both
the sorted() function and .sort() method accept a key
argument.
b. The value passed to this argument needs to be a function
object that returns the sorting key for any item in the list
or iterable.
3. For example : Consider the given list of tuples, Python will
sort by default on the first value in each tuple. In order to sort
on a different element from each tuple, a function can be
passed that return that element.
>>> def second_element (t) :
... return t[1]
...
>>> zepp = [(‘Guitar’, ‘Jimmy’), (‘Vocals’, ‘Robert’), (‘Bass’, ‘John
Paul’), (‘Drums’, ‘John’)]
>>> sorted(zepp)
[(‘Bass’, ‘John Paul’), (‘Drums’, ‘John’), (‘Guitar’, ‘Jimmy’),
(‘Vocals’, ‘Robert’)]
5. Insertion sort :
a. Insertion sort involves finding the right place for a given
element in a sorted list. So in beginning we compare the first
two elements and sort them by comparing them.
b. Then we pick the third element and find its proper position
among the previous two sorted elements.
c. This way we gradually go on adding more elements to the
already sorted list by putting them in their proper position.
Solved Paper (2019-20) SP–40 T (CC-Sem-3 & 4)
For example :
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j=i–1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j – 1
InputList[j+1] = nxt_element
list = [19,2,30,42,28,11,135,26]
insertion_sort(list)
print(list)
Program for Sieve of Eratosthenes :
def SieveOf Eratosthenes (n) :
# Create a boolean array “prime[0. . n]” and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in range(n+1)]
p=2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p+=1
# Print all prime numbers
for p in range(2, n):
if prime[p]:
print p,
# driver program
if__name__‘==’__main__’:
n = 30
print “Following are the prime numbers smaller”,
print “than or equal to”, n
SieveOfEratosthenes(n)