0% found this document useful (0 votes)
4 views

Python-programming-askbooks.net_ (1)

The document covers the Sieve of Eratosthenes algorithm for finding prime numbers, including its explanation and a Python implementation. It also discusses file input/output operations in Python, including how to open, read, write, and close files. Additionally, it introduces assertions in programming, explaining their purpose and usage in error checking.

Uploaded by

Nandni Arya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python-programming-askbooks.net_ (1)

The document covers the Sieve of Eratosthenes algorithm for finding prime numbers, including its explanation and a Python implementation. It also discusses file input/output operations in Python, including how to open, read, write, and close files. Additionally, it introduces assertions in programming, explaining their purpose and usage in error checking.

Uploaded by

Nandni Arya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

Python Programming 4–1 T (CC-Sem-3 & 4)

4 Sieve of Eratosthenes
and File I/O

CONTENTS
Part-1 : Sieve of Eratosthenes ................................ 4–2T to 4–4T

Part-2 : File I/O : File Input and .............................. 4–4T to 4–7T


Output Operations in
Python Programming

Part-3 : Exceptions and Assertions ...................... 4–7T to 4–13T

Part-4 : Modules : Introduction, .......................... 4–13T to 4–17T


Importing Modules, Abstract
Data Types : Abstract Data
Types and ADT Interface
in Python Programming

Part-5 : Classes : Class Definition ...................... 4–17T to 4–22T


and other Operations in the
Classes, Special Methods
(Such as__init__, __str__,
Comparison Methods,
Arithmetic Methods,
etc.), Class Example

Part-6 : Inheritance : ............................................. 4–22T to 4–32T


Inheritance and OOPS
Sieve of Eratosthenes and File I/O 4–2 T (CC-Sem-3 & 4)

Sieve of Eratosthenes.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 4.1. What is Sieve of Eratosthenes ?

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.

Que 4.2. Explain Sieve of Eratosthenes with example.

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

Que 4.3. Write a Python program to print all primes smaller


than or equal to n using Sieve of Eratosthenes.

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)

# 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)

File I/O : File Input and Output Operations


in Python Programming.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 4.4. What are files ? How are they useful ?

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.

Que 4.5. Describe the opening a file function in Python.


Python Programming 4–5 T (CC-Sem-3 & 4)

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

Que 4.6. Explain the closing a file method in Python.

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

Que 4.7. Discuss writing to a file operation.


Sieve of Eratosthenes and File I/O 4–6 T (CC-Sem-3 & 4)

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

Que 4.8. Explain reading from a file operation with example.

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)

>>> f = open (“C :/Python27/test.txt”, “r”)


>>>f . read (7) # read from starting 7 bytes of data
‘writing’ # Output
>>>f. read (6) # read next 6 bytes of data
‘to the’ # Output

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

Exception and Assertions.

Questions-Answers

Long Answer Type and Medium Answer Type Questions


Sieve of Eratosthenes and File I/O 4–8 T (CC-Sem-3 & 4)

Que 4.10. Describe assertions.

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!

Que 4.11. What do you mean by exceptions ?

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)

2. The error caused by writing an improper syntax is termed syntax error


or parsing error; these are also called compile time errors.
3. Errors can also occur at runtime and these runtime errors are known
as exceptions.
4. There are various types of runtime error in Python.
5. For example, when a file we try to open does not exist, we get a
FileNotFoundError. When a division by zero happens, we get a
ZeroDivisionError. When the module we are trying to import does not
exist, we get an ImportError.
6. Python creates an exception object for every occurrence of these run-
time errors.
7. The user must write a piece of code that can handle the error.
8. If it is not capable of handling the error, the program prints a trace back
to that error along with the details of why the error has occurred.
For example :
Compile time error (syntax error)
>>> a = 3
>>> if (a < 4) # semicolon is not included
SyntaxError : invalid syntax # Output
ZeroDivisionError :
>>>5/0
Output :
Traceback (most recent call last) :
File “<pyshell#71>”, line 1, in <module>
5/0
ZeroDivisionError : Integer division or modulo by zero
Que 4.12. Explain exceptions handling with syntax.

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.

Que 4.13. Give example of try….except.

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

Que 4.14. Give example of try….finally.

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.

Que 4.15. Discuss exceptions and assertions in Python. How to


handle exceptions with try-finally ? Explain five built-in exceptions
with example. AKTU 2019-20, Marks 10

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’

Modules : Introduction, Importing Modules, Abstract Data Types :


Abstract Data Types and ADT Interface in Python Programming.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 4.16. Define the term modules.

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

Que 4.18. Explain abstract data types with its types.

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.

Que 4.19. Explain ADT interface in Python programming.

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.

Abstract Data Type

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

for a student information. AKTU 2019-20, Marks 10

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)

# 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;
# Create a list to add Students
ls =[ ]
# an object of Student class
obj = Student(‘ ’, 0, 0, 0)
print(“\nOperations used, ”)
print(“\n1.Accept Student details\n2.Display Student Details\n”/
/“3.Search Details of a Student\n4.Delete Details of Student” /
/“\n5.Update Student Details\n6.Exit”)
ch = int(input(“Enter choice:”))
if(ch == 1):
obj.accept(“A”, 1, 100, 100)
obj.accept(“B”, 2, 90, 90)
obj.accept(“C”, 3, 80, 80)
elif(ch == 2):
print(“\n”)
print(“\nList of Students\n”)
for i in range(ls.__len__()):
obj.display(ls[i])
elif(ch == 3):
print(“\n Student Found,”)
s = obj.search(2)
Python Programming 4–17 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 !”)

Classes : Class Definition and other Operations in the Classes,


Special Methods (Such as__init__, __str__, Comparison
Methods, Arithmetic Methods, etc.), Class Example.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 4.21. Define class.

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)

Que 4.22. What do you mean by objects ?

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.

Que 4.23. Give an example of class.

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.

Que 4.24. Explain object creation with the help of example.

Answer
>>>class Student :
... ‘student details’
... def fill_details(self, name, branch, year):
... self.name = name
Python Programming 4–19 T (CC-Sem-3 & 4)

... 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)
# creating an object of Student class
>>>s1 = Student ()
# creating another object of Student class
>>>s2 = Student ()
# using the method fill_details with proper attributes
>>> s1.fill_details(‘John’,‘CSE’,‘2002’)
A Student detail object is created
>>>s2.fill_details(‘Jack’,‘ECE’,‘2004’)
A Student detail object is created
# using the print_details method with proper attributes
>>>s1.print_details ()
Name : John # Output
Branch : CSE # Output
Year : 2002 # Output
>>>s2.print_details()
Name : Jack # Output
Branch : ECE # Output
Year : 2004 # Output

Que 4.25. Discuss the __init__ function in detail with example.

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.

Que 4.26. What is __str__ method in class ?

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’

Que 4.27. Define the comparison method.


Python Programming 4–21 T (CC-Sem-3 & 4)

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.

Que 4.28. Explain various arithmetic methods in detail.

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)

a, b, c, d = self.lo, self.up, other.lo, other.up


return IntervalMath (a + c, b + d)
def __sub__(self, other) :
a, b, c, d = self. lo, self. up, other. lo, other. up
return IntervalMath (a – d, b – c )
def __mul__(self, other) :
a, b, c, d = self.lo, self.up, other.lo, other.up
return IntervalMath(min(a*c, a*d, b*c, b*d),
max(a*c, a*d, b*c, b*d))
def __div__(self, other):
a, b, c, d = self.lo, self.up, other.lo, other.up
# [c,d] cannot contain zero:
if c*d <= 0:
raise ValueError\
(‘Interval %s cannot be denominator because ‘\’
it contains zero’ % other)
return IntervalMath(min(a/c, a/d, b/c, b/d), max(a/c, a/d, b/c, b/d))
The code of this class is found in the file IntervalMath.py.
I = IntervalMath
a = I(– 3, – 2)
b = I(4, 5)
expr = ‘a + b’, ‘a – b’, ‘a*b’, ‘a/b’
for e in expr :
print ‘%s =’ % e, eval(e)
Output :
a + b = [1, 3]
a – b = [– 8, – 6]
a * b = [– 15, – 8]
a / b = [– 0.75, – 0.4]

Inheritance : Inheritance and OOPS.

Questions-Answers

Long Answer Type and Medium Answer Type Questions


Python Programming 4–23 T (CC-Sem-3 & 4)

Que 4.29. What is object-oriented programming ?

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)

Name: Jack # Output

Que 4.32. What do you mean by multiple inheritance ? Explain in


detail.

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

Fig. 4.32.1. Multiple inheritance.

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.

Que 4.33. Define method overriding with the help of example.

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

Que 4.34. Describe the term polymorphism.

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 ()

Class Triangle Class Circle Class Square


Draw () Draw () Draw ()

Fig. 4.34.1. Pythomorphism.

Que 4.35. Explain data encapsulation with example.

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’

Que 4.36. Discuss data hiding in detail.

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)

AttributeError : MyClass instance has no attribute ‘__a’


3. In the given example, the variable a is not accessible as we tried to
access it; the Python interpreter generates an error immediately.
4. In such a case, the Python secures the members by internally changing
the names, to incorporate the name of the class.
5. In the given code, if we use the aforementioned syntax to access the
attributes, then the following changes are seen in the output:
>>> class MyClass : # Defining class
__a = 0;
def sum (self, increment):
self. __a += increment
print self. __a
>>> b = MyClass() # Creating instance of class
>>> b.sum(2)
2 #Output
>>> b.sum(5)
7 #Output
>>> print b._ MyClass_a # Accessing the hidden variable
7 #Output

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

Part-2 : Search : Simple Search and .................... 5–7T to 5–10T


Estimating Search Time,
Binary Search and Estimating
Binary Search Time

Part-3 : Sorting and Merging : ............................ 5–10T to 5–18T


Selection Sort, Merge List,
Merge Sort, Higher
Order Sort
Iterators and Recursion 5–2 T (CC-Sem-3 & 4)

Iterators and Recursion : Recursive Fibonacci, Tower of Hanoi.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 5.1. What do you mean by iterator ?

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)

# Stop iteration if limit is reached


if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)
Output :
10
11
12
13
14
15

Que 5.2. Define recursion. Also, give example.

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

Que 5.3. Explain Fibonacci series using Python.


Iterators and Recursion 5–4 T (CC-Sem-3 & 4)

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.

Que 5.4. Explain Tower of Hanoi problem in detail.


OR
Explain iterator. Write a program to demonstrate the Tower of
Hanoi using function. AKTU 2019-20, Marks 10

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.

4. Recursive Python function to solve Tower of Hanoi


def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n==1:
print “Move disk 1 from rod”,from_rod,“to rod”,to_rod
return
TowerOfHanoi(n – 1, from_rod, aux_rod, to_rod)
print “Move disk”,n,“from_rod”,from_rod,“to rod”,to_rod
TowerOfHanoi(n – 1, aux_rod, to_rod, from_rod)
n=4
TowerOfHanoi(n, \‘A\’, \‘C\’, \‘B\’)
# A, C, B are the name of rods
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
Iterators and Recursion 5–6 T (CC-Sem-3 & 4)

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

Que 5.5. Differentiate between recursion and iteration.


OR
Discuss and differentiate iterators and recursion. Write a program
for recursive Fibonacci series. AKTU 2019-20, Marks 10

Answer

Property Recursion Iteration

Definition Function calls itself. A set o f instructio n


repeatedly executed.
Application For functions. For loops.
Termination Through base case, When the te rmination
where there will be no condition for the iterator
function call. ceases to be satisfied.
Usage Used when code size Used when time
need to be small, and complexity needs to be
time complexity is not balanced against an
an issue. expanded code size.
Code size Smaller code size. Larger code size.
Time Very high (generally Relatively lower time
Complexity exponential) time complexity (generally
complexity. polynomial logarithmic).
Stack The stack is used to Does not use stack.
store the set of new
local variables and
parameters each time
the function is called.
Overhead Recursion possesses No overhead of repeated
the overhead of function call.
repeated function calls.
Speed Slow in execution. Fast in execution.
Python Programming 5–7 T (CC-Sem-3 & 4)

Program for recursive Fibonacci series : Refer Q. 5.3, Page 5–3T,


Unit-5.

Search : Simple Search and Estimating Search Time,


Binary Search and Estimating Binary Search Time.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

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

Que 5.7. Explain the time complexity for linear search.


Iterators and Recursion 5–8 T (CC-Sem-3 & 4)

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).

Que 5.8. Discuss binary search in Python.

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

Que 5.9. Explain the time complexity for binary search.

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)

Recursive function of binary search :


T(n) = T(n/2) + 1
T(n/2) = T(n/4) + 1 + 1
Put the value of T(n/2) in above so
T(n) = T(n/4) + 1 + 1...T(n/2k) + 1 + 1
= T(2k/2k) + 1 + 1...+ 1 upto k
= T(1) + k
As we taken 2k = n
k = log n
So time complexity is O(log n)
4. We have three cases to analyse an algorithm :
a. Best case :
i. In the best case, the item x is the middle in the array A. A
constant number of comparisons (actually just 1) are required.
ii. Time complexity in best case is O(1).
b. Worst case :
i. In the worst case, the item x does not exist in the array A at all.
Through each recursion or iteration of binary search, the size
of the admissible range is halved.
ii. Time complexity in worst case is O(log n).
c. Average case :
i. To find the average case, take the sum over all elements of the
product of number of comparisons required to find each element
and the probability of searching for that element.
ii. Time complexity in average case is O(log n).

Sorting and Merging : Selection Sort, Merge List, Merge Sort,


Higher Order Sort.

Questions-Answers

Long Answer Type and Medium Answer Type Questions

Que 5.10. What do you mean by selection sort ? Discuss in detail.


Python Programming 5–11 T (CC-Sem-3 & 4)

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)

Que 5.11. Explain merge list.

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)

n1=int(input(“Enter number of elements:”))


for i in range(1, n1+1):
b=int(input(“Enter element:”))
a.append(b)
n2=int(input(“Enter number of elements:”))
for i in range(1, n2+1):
d=int(input(“Enter element:”))
c.append(d)
new=a+c
new.sort( )
print(“Sorted list is:”, new)

Que 5.12. Explain merge sort with the help of example.

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)

Assume n = 2k for some k.


k = log2 n
Then, T(n) = n*T(1) + Cn*log2n
i. Time complexity of Merge sort is O(n log n) in all three cases (worst,
average and best) as merge sort always divides the array into two halves
and take linear time to merge two halves.

Que 5.13. Discuss higher order sort.

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’)]

Que 5.14. Discuss sorting and merging. Explain different types of


sorting with example. Write a Python program for Sieve of
Eratosthenes. AKTU 2019-20, Marks 10

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.

Que 5.15. What will be the output after the following


statements ?
x = [25, 14, 53, 62, 11]
x.sort()
print(x)

Answer
[11, 14, 25, 53, 62]

Que 5.16. What will be the output after the following


statements ?
x = [‘25’, ‘Today’, ‘53’, ‘Sunday’, ‘15’]
x.sort()
print(x)

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’]

Que 5.19. What will be the output after the following


statements ?
x = [‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’]
x.sort(key=str.lower)
print(x)

Answer
[‘a’, ‘A’, ‘b’, ‘B’, ‘c’, ‘C’]

Que 5.20. What will be the output after the following


statements ?
x = [‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’]
x.sort(key=str.swapcase)
print(x)

Answer
[‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’]

Que 5.21. What will be the output after the following


statements ?
x = [‘a’, ‘b’, 1, 2, ‘A’, ‘B’]
x.sort()
print(x)

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)

1.1. What is Python ?


Ans. Python is a high-level, interpreted, interactive and object-oriented
scripting language. It is a highly readable language. Unlike other
programming languages, Python provides an interactive mode
similar to that of a calculator.

1.2. What are the difference between Java and Python ?


Ans.
Features Java Python
Syntax The syntax o f Java is The syntax of Python is
complex than Python. easier than Java.
Speed Java is statically typed Python is manually typed,
programming, makes it makes it slower.
faster.
Code Longer lines of code than Shorter lines of code than
Python. Java.

1.3. What are the features of Python ?


Ans. Features of Python :
1. The code written in Python is automatically compiled to byte code
and executed.
2. Python can be used as a scripting language, as a language for
implementing web applications, etc.
3. Python supports many features such as nested code blocks,
functions, classes, modules and packages.
4. Python makes use of an object oriented programming approach.
5. It has many built-in data types such as strings, lists, tuples,
dictionaries, etc.

1.4. What are the different ways of starting Python ?


Ans. There are three different ways of starting Python :
1. Running a script written in Python.
2 Marks Questions SQ–2 T (CC-Sem-3 & 4)

2. Using a graphical user interface (GUI) from an Integrated


Development Environment (IDE),
3. Employing an interactive approach.

1.5. Which character is used for commenting in Python ?


Ans. Hash mark (#) is used for commenting in Python.

1.6. How is Python an interpreted language ?


AKTU 2019-20, Marks 02
Ans. Python is called an interpreted language because it goes through
an interpreter, which turns the Python code into the language
understood by processor of the computer.

1.7. What type of language is python ?


AKTU 2019-20, Marks 02
Ans. Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics.

1.8. Define the type () function.


Ans. Type () function in Python programming language is a built-in
function which return the datatype of any arbitrary object. The
object is passed as an argument to the type() function. Type()
function can take anything as an argument and return its datatype,
such as integers, strings, dictionaries, lists, classes, module, tuple,
functions, etc.

1.9. Define the unary operator.


Ans. Unary operators are operators with only one operand. These
operators are basically used to provide sign to the operand.
+, –, ~ are some unary operators.

1.10. What do you mean by binary operator ?


Ans. Binary operators are operators with two operands that are
manipulated to get the result. They are also used to compare numeric
values and string values.
**, %, <<, >>, &, |, ^, <, >, <=, >=, ==, !=, <> are some binary
operators.

1.11. What is the purpose of PYTHONPATH environment


variable ?
Ans. Pythonpath has a role similar to PATH. This variable tells Python
Interpreter where to locate the module files imported into a
program. It should include Python source library directory and
the directories containing Python source code. PYTHONPATH is
sometimes preset by Python Installer.
Python Programming SQ–3 T (CC-Sem-3 & 4)

1.12. What is the difference between list and tuples in Python ?


AKTU 2019-20, Marks 02
Ans.
S. No. List Tuples
1. Lists are mutable, i.e., they Tuples are immutable (they are
can be edited. lists that cannot be edited).
2. Lists are usually slower than Tuples are faster than lists.
tuples.
3. Syntax : Syntax :
list_ 1 = [10, ‘Quantum’, 20] tup_ 1 = (10, ‘Quantum’, 20)

1.13. What is the difference between Python arrays and lists.

AKTU 2019-20, Marks 02

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.

1.14. Can we make multiline comments in Python ?


Ans. Python does not have a specific syntax for including multiline
co mments like othe r programming languages. Ho weve r,
programmers can use triple-quoted strings (docstrings) for making
multiline comments as when a docstring is not used as the first
statement inside a method, it is ignored by Python parser.

1.15. Do we need to declare variables with data types in Python ?


Ans. No. Python is a dynamically typed language, i.e., Python
Interpreter automatically identifies the data type of a variable
based on the type of value assigned to the variable.
2 Marks Questions SQ–4 T (CC-Sem-3 & 4)

1.16. In some languages, every statement ends with a semi-colon


(;). What happens if you put a semi-colon at the end of a
Python statement ? AKTU 2019-20, Marks 02
Ans. Python allows semicolon to use as a line terminator. So no error
will occur if we put a semi-colon; at the end of python statement.

1.17. Mention five benefits of using Python.


AKTU 2019-20, Marks 02

Ans. Benefits of Python :


1. Python is easy to learn.
2. Most automation, data mining, and big data platforms depend on
Python. This is because it is the ideal language to work with for
general purpose tasks.
3. Python provides productive coding environment.
4. It supports extensive libraries.
5. Python uses different frameworks to simplify the development
process.

1.18. Define floor division with example.


AKTU 2019-20, Marks 02

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.19. List some Python IDEs.


Ans. Some Python IDEs are :
1. PyCharm
2. Spyder
3. PyDev

1.20. Mention some of the reserved keyword in Python.


Ans.
1. and
2. false
3. is
4. pass
5. return
6. def
Python Programming SQ–5 T (CC-Sem-3 & 4)

1.21. Give an example of assigning one variable value to another.


Ans. >>> name1 = ‘Albert’
>>> name2 = name1
>>> name2
‘Albert’ # Output
>>>

1.22. Give an example of different types of values to the same


variable.
Ans. >>> amount = 50
>>> amount
50 # Output
>>> amount = ‘Fifty’
>>> amount
‘Fifty’ # Output
>>>

1.23. What are the types of type conversion ?


Ans. Two types of type conversion are :
1. Implicit type conversion
2. Explicit type conversion

1.24. What are types of assignment statements ?


Ans. Three type of assignment statements are :
1. Value-based expression on RHS
2. Current variable on RHS
3. Operation on RHS

1.25. List the categories of operators.


Ans. Following are the seven categories of operators :
1. Arithmetic operators.
2. Assignment operators.
3. Bitwise operators.
4. Comparison operators.
5. Identity operators.
6. Logical operators.
7. Membership operators.

1.26. Name the tools that are used for static analysis.
Ans.
1. Pychecker
2. Pylint

1.27. What are the different data types used in Python ?


Ans. Python has six basic data types which are as follows :
1. Numeric
2 Marks Questions SQ–6 T (CC-Sem-3 & 4)

2. String
3. List
4. Tuple
5. Dictionary
6. Boolean

1.28. Define operator associativity with its type.


Ans.
1. Associativity decides the order in which the operators with same
precedence are executed.
2. There are two types of associativity :
a. Left to right : In left to right associativity, the operator of
same precedence are executed from the left side first.
b. Right to left : In right to left associativity, the operator of
same precedence are executed from the right side first.


Python Programming SQ–7 T (CC-Sem-3 & 4)

2 Conditionals and Loops


(2 Marks Questions)

2.1. What are the factors for expression evaluation ?


Ans.
1. Precedence : It is applied to two different class of operators. That
is, + and*, – and *, AND & OR, etc.
2. Associativity : It is applied to operators of same class. That is, *
and *, + and –, * and /, etc.
3. Order : Precedence and associativity identify the operands for each
operator. While evaluating an assignment, the RHS is evaluated
before LHS.

2.2. What is range () function ?


Ans. The range () function is a built-in function in Python that helps us
to iterate over a sequence of numbers. It produces an iterator that
follows arithmetic progression.

2.3. Give an example of range () function.


Ans. >>> range (8)
[0, 1, 2, 3, 4, 5, 6, 7]
range (8) provides a sequence of number 0-7. That is to say range
(n) generates a sequence of number that starts with 0 and end with
(n – 1).

2.4. Explain begin and end arguments passed by range ()


function.
Ans. >>> range (3, 9)
[3, 4, 5, 6, 7, 8]
We provided the begin index with 3 and the end index with 9.
Hence, the range function generates a sequence iterator of number
that starts from 3 and ends at 8.

2.5. Define the term alternative execution.


Ans. The alternative execution provides two possibilities and the condition
determines which one is to be executed. This is the second form of
the if statement.
2 Marks Questions SQ–8 T (CC-Sem-3 & 4)

2.6. What do you mean by block ?


Ans. The intended statements that follow the conditional statements
are called block. The first unintended statement marks the end of
the block.

2.7. What will be the output of the following code :


Str [0 : 4] if str=“Hello”
Ans. ‘Hello’

2.8. What are control statements ?


Ans. A control statement is a statement that determines the control flow
of a set of instructions. There are three fundamental forms of
control that programming languages provide: sequential control,
selection control, and iterative control.

2.9. What is short-circuit evaluation ?


Ans. In short-circuit (lazy) evaluation, the second operand of Boolean
operators AND and OR is not evaluated if the value of the Boolean
expression can be determined from the first operand alone.

2.10. Define the terms : header, suite and clause.


Ans. A header in Python starts with a keyword and ends with a colon.
The group of statements following a header is called a suite. A
header and its associated suite are together referred to as a clause.

2.11. What do you mean by iterative control ?


Ans. An iterative control statement is a control statement providing the
repeated execution of a set of instructions. An iterative control
structure is a set of instructions and the iterative control
statement(s) controlling their execution.

2.12. What do you mean by definite loop ?


Ans. A definite loop is a program loop in which the number of times the
loop will iterate can be determined before the loop is executed.

2.13. What do you mean by indefinite loop ?


Ans. An indefinite loop is a program loop in which the number of times
that the loop will iterate cannot be determined before the loop is
executed.

2.14. Is indentation optional in Python ?


Ans. No indentation in Python is compulsory and is part of its syntax.
Indentation is a way of defining the scope and extent of the block of
codes. Indentation provides better readability to the code.
Python Programming SQ–9 T (CC-Sem-3 & 4)

2.15. What happen if break statement is used in for loop ?


Ans. If the break statement in a for loop is executed then the else part of
that for loop is skipped.

2.16. What is raw_input ( ) function ?


Ans. Raw_input ( ) takes the input from the user but it does not interpret
the input and also it returns the input of the user without doing any
changes.

2.17. Differentiate fruitful functions and void functions.


AKTU 2019-20, Marks 02
Ans. The main difference between void and fruitful function in python
is :
1. Void does not return any value
2. Fruitful function returns some value


2 Marks Questions SQ–10 T (CC-Sem-3 & 4)

3 Functions and Strings


(2 Marks Questions)

3.1. Define traversing of string. Give an example.


Ans. Traversal is a process in which we access all the elements of the
string one by one using some conditional statements such as for
loop, while loop, etc.
For example :
>>> var = ‘jack john’
>>> i = 0
>>> while i < len (var) :
... x = var [i]
... print x
... i = i + 1
Output :
j
a
c
k
j
o
h
n

3.2. What are escape characters ?


Ans. The backslash character (/) is used to escape characters. It converts
difficult-to-type characters into a string. For example, we need the
escaping character concept when we want to print a string with
double quotes or single quotes. When single or double quotes are
used with the string, Python normally neglects them and prints
only the string.

3.3. What do you mean by tuple assignment ?


Ans. Tuple assignment allows the assignment of values to a tuple of
variables on the left side of assignment from the tuple of values on
the right side of the assignment.
Python Programming SQ–11 T (CC-Sem-3 & 4)

3.4. What do you mean by “Lists are mutable” ?


Ans. Lists are mutable means that we can change the value of any
elements inside the list at any point of time. The element inside the
list are accessible with their index value. The index will always start
with 0 and end with n – 1, if the list contains n elements.

3.5. What do you understand by traversing a list ?


Ans. Traversing of the list refers to accessing all the elements or items of
the list. Traversing can be done using any conditional statement of
Python, but it is preferable to use for loop.

3.6. What are the different methods used in deleting elements


from dictionary ?
Ans. Methods used in deleting elements from dictionary are :
1. pop( ) : pop() method removes that item from the dictionary for
which the key is provided. It also returns the value of the item.
2. popitem( ) : popitem() method is used to remove or delete and
return an arbitrary item from the dictionary.
3. clear( ) : clear() method removes all the items or elements from a
dictionary at the same time.

3.7. What are the two properties of key in the dictionary ?


Ans. Properties of key :
1. One key in a dictionary cannot have two values, i.e., duplicate keys
are not allowed in the dictionary; they must be unique.
2. Keys are immutable, i.e., we can use string, integers or tuples for
dictionary keys, but cannot use something like [‘key’].

3.8. Why we use functions ?


Ans.
1. Break up complex problem into small sub-programs.
2. Solve each of the sub-problems separately as a function, and combine
them together in another function.
3. Hide the details and shows the functionality.

3.9. What are mathematical functions ? How are they used in


Python ?
Ans. Python provides us a math module containing most of the familiar
and important mathematical functions. A module is a file that
contain some predefine Python codes. A module can define
functions, classes and variables. It is a collection of related functions
grouped together.
Before using a module in Python, we have to import it
For example, to import the math module, we use :
>>> import math

3.10. What are user-defined functions ? Give the syntax.


2 Marks Questions SQ–12 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.11. Define the return statement in a function. Give the syntax.


Ans. The return statement is used to exit a function. A function may or
may not return a value. If a function returns a value, it is passed
back by the return statement as argument to the caller. If it does
not return a value, we simply write return with no arguments.
Syntax :
return [expression]

3.12. Define anonymous function.


Ans. The anonymous functions are the functions created using a lambda
keyword.

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.14. An email address is provided : hello@python. org. Using


tuple assignment, split the username and domain from the
email address.
Ans. >>> addr = ‘hello@python. org’
>>> usrname, domain = addr. split (‘@’)
>>> print usrname
Hello # Output
>>> print domain
python. org # Output

3.15. Write a function called sumall that takes any number of


arguments and returns their sum.
Python Programming SQ–13 T (CC-Sem-3 & 4)

Ans. >>> def suma11 (*t) :


i=0
sum = 0
whilei < len(t) :
sum = sum + t[i]
i=i+1
return sum
>>>suma11(1, 2, 3, 4, 5, 6, 7)
28 # Output

3.16. Write a function called circleinfo which takes the radius of


circle as argument and returns the area and circumference
of the circle.
Ans. >>>def circleinfo(r) :
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
>>> circleinfo(10)
(62.8318, 314.159) # Output

3.17. Give examples for len, max and min methods.


Ans. >>> list = [789, ‘abcd’, ‘jinnie’, 1234]
>>> len(list)
4 # Output
>>> max(list)
‘jinnie’ # Output
>>>min(list)
789 # 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

3.19. Give the syntax required to convert an integer number into


string and a float to an integer.
Ans. # integer to string
>>>str (5)
‘5’ # Output
# float to integer
2 Marks Questions SQ–14 T (CC-Sem-3 & 4)

>>>float (5.50)
5 # Output

3.20. Write a program to print the calendar for the month of


March 1991.
Ans. >>> import calendar
>>> c = calender.month(1991, 3)
>>> print c
March 1991
Mo Tu We Th Fr Sa Su
1 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

3.21. Write a function which accepts two numbers and returns


their sum.
Ans. >>> def sum (arg1, arg2) :
sum = arg1 + arg2
return sum
# Now calling the function here
>>> a = 4
>>> b = 3
>>> total = sum(a, b) # calling the sum function
>>> print(total)
7 # 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

3.24. What is slicing ?


Ans. In Python, we can extract a substring by using a colon inside the
square bracket [:]. The resultant substring is a part of the long
string.

3.25. What is the use of docstring ?


Ans. Docstring command is use to know about a function using triple-
quoted string.

3.26. What are local variables and global variables in Python ?


AKTU 2019-20, Marks 02
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.


2 Marks Questions SQ–16 T (CC-Sem-3 & 4)

4 Sieve of Eratosthenes
and File I/O
(2 Marks Questions)

4.1. What is class variable ?


Ans. A variable that is defined in the class and can be used by all the
instances of that class is called class variable.

4.2. Define instance variable.


Ans. A variable that is defined in the method; its scope is only within the
object that defines it.

4.3. Define the term instance.


Ans. An object is an instance of the class.

4.4. What do you mean by instantiation ?


Ans. The process of creating an object is called instantiation.

4.5. Define function overloading.


Ans. A function defined more than one time with different behaviours is
called function overloading.

4.6. What do you mean by methods ?


Ans. Methods are the functions defined in the definition of class and are
used by various instances of the class.

4.7. How are the objects created in Python ? Give an example.


Ans. Objects can be used to access the attributes of the class. The syntax
for creating an object in Python is similar to that for calling a
function.
Syntax :
obj_name = class_name ()
For example :
# define a class
>>>class A :
def print_det (self) :
print ‘This is a class’
Python Programming SQ–17 T (CC-Sem-3 & 4)

# create object of class A


>>> object = A()
>>> object. print_det()
This is a class # Output

4.8. What do you understand by “Objects are mutable” ?


Ans. Objects are mutable means that the state of an object can be changed
at any point in time by making changes to its attributes.

4.9. What do you understand by arguments “Instances as return


values” ?
Ans. The instances of a class can also be returned by a function i.e.,
function can return the instances or objects.

4.10. Define__dict__, __bases__, __name__ built-in class attributes.


Give example.
Ans. __dict__ : It displays the dictionary in which the namespace of class
is stored.
__name__ : It displays the name of the class.
__bases__ : It displays the tuple that contains the base classes,
possibly empty. It displays them in the order in which they occur in
the base class list.
For example :
>>> print “__name__ :”, PrintStatement.__name__
__name__ : PrintStatement
>>> print “__bases__ :”, PrintStatement __bases__
__bases__ : ()
>>>print “PrintStatement”.__dict__: “PrintStatment” __dict__
PrintStatement.__dict__ : {‘__module__’ : ‘__main__’, ‘__doc__’ :
None, ‘print_method’ : < function print_method at 0x.2CE3130>}

4.11. Give the advantage of inheritance.


Ans. The main advantage of inheritance is that the code can be written
once in the base class and then reused repeatedly in the subclasses.

4.12. Define subclass.


Ans. The class which inherits the feature of another class is called
subclass.

4.13. List the order of file operations in Python.


Ans. The order is as follows :
1. Opening a file
2. Perform read or write operation
3. Closing a file

4.14. Explain any four modes of opening the file.


2 Marks Questions SQ–18 T (CC-Sem-3 & 4)

Ans. Modes of opening the file :


i. r : It opens a file in reading mode. The file pointer is placed at the
starting of the file.
ii. r + : It opens the file in both reading and writing mode. The file
pointer is placed at the starting of the file.
iii. w : It opens the file in writing mode. If a file exists, it overwrites the
existing file; otherwise, it creates a new file.
iv. w + : It opens the file in both reading and writing mode. If a file
exists, it overwrites the existing file; otherwise, it creates a new
file.

4.15. Explain the file object attributes in detail.


Ans.
Attribute Description
file.closed It will return true if the file is closed ; it will
otherwise return false.
file.mode It will return the access mode with which the
file is opened.
file.name It will return name of the file
file.softspace It will return false if space explicitly required
with print; otherwise it will return true.

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.

4.17. How are renaming and deleting performed on a file ? Give


the syntax for each.
Ans. Renaming a file : Renaming a file in Python is done with the help
of the rename() method. The rename() method is passed with two
argument, the current filename and the new filename.
Syntax :
os.rename(current_filename, new_filename)
Deleting a file : Deleting a file in Python is done with the help of
the remove() method. The remove() method takes the filename as
an argument to be deleted.
Syntax :
os.remove(filename)
Python Programming SQ–19 T (CC-Sem-3 & 4)

4.18. What are the various file positions methods ?


Ans. In Python, the tell() method tells us about the current position of
the pointer. The current position tells us where reading will starts
from at present.
We can also change the position of the pointer with the help of the
seek() method. We pass the number of bytes to be moved by the
pointer as arguments to the seek() method.

4.19. What are directories ?


Ans. If there is a large number of file, then related files are placed in
different directories. Directory can be said to be a collection of files
and sub directories. The module os in Python enables us to use
various methods to work with directories.

4.20. What are the basic methods performed on directories ?


Ans. Following are the four basic methods that are performed on
directories :
i. mkdir () method (Creating a directory)
ii. chdir() method (Changing the current directory)
iii. getcwd () method (Displaying the current directory)
iv. rmdir () method (Deleting the directory).

4.21. What are user-defined exceptions ? Give one example.


Ans. Python allows users to define their own exceptions by creating a
new class. Exception needs to be derived, directly or indirectly from
exception class.
For example :
>>> class error(Exception)
pass

4.22. Write some built-in exception in Python.


Ans.
i. AssertionError
ii. FloatingPointError
iii. SystemError
iv. RunTimeError
v. ZeroDivisionError

4.23. Define ADT interface. AKTU 2019-20, Marks 02


Ans. ADT interface only define as what operations are to be performed
but not how these operations will be implemented. It does not
specify how data will be organized in memory and what algorithms
will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view.


2 Marks Questions SQ–20 T (CC-Sem-3 & 4)

5 Iterators and
Recursion
(2 Marks Questions)

5.1. What are properties of recursive functions ?


Ans. Properties of recursive function :
1. The arguments of function change between the recursive calls.
2. The change in arguments should be toward a case for which the
solution is known and we call it as a base case. There can be more
than one base case.

5.2. What are the advantages of recursion ?


Ans.
1. It requires few variables.
2. The programs are easy to implement if the problem has a recursive
definition.

5.3. Give some disadvantages of recursion.


Ans.
1. Debugging is difficult.
2. It is not easy to write the program in a recursive form.
3. It can be inefficient as it requires more time and space.

5.4. What are the applications of Tower of Hanoi problem ?


Ans.
1. The Tower of Hanoi is frequently used in psychological research on
problem solving.
2. There also exists a variant of this task called Tower of London for
neuropsychological diagnosis and treatment of executive functions.
3. The Tower of Hanoi is also used as a Backup rotation scheme when
performing computer data Backups where multiple tapes/media
are involved.
4. The Tower of Hanoi is also used as a test by neuropsychologists
trying to evaluate frontal lobe deficits.

5.5. What are the advantages and drawbacks of simple search ?


Ans. Advantages :
1. It is a very simple search and easy to program.
2. In the best-case scenario, the item we are searching for may be at
the start of the list in which case we get it on the very first try.
Python Programming SQ–21 T (CC-Sem-3 & 4)

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.

5.6. Write algorithm of simple search.


Ans. if start > end:
return False
if a[start]==key:
return True
return search(a, start + 1, end, key)

5.7. Give the algorithm for binary search.


Ans. if start > end :
return False
mid = (start + end) //2
if a [mid] = = key:
return True
if (a[mid] > key):
return binsearch(a, start, mid – 1, key)
else :
return binsearch(a, mid + 1, end, key)

5.8. Define the term sorting.


Ans.
1. Sorting is the arrangement of a given list in ascending order or
descending order.
2. In sorting, searching for an element is very fast.
3. Example of sorting in real world are : Contact list in mobile phones,
ordering marks before assignment of grades, etc.

5.9. Write the complexity of sorting algorithm.


Ans.
1. Merge sort : O(n log n)
2. Selection sort : O(n2)
3. Bouble sort : O(n2)

5.9. Which operation is used to implement merge sort ?


Ans. Merge operation is used to implement merge sort.

5.11. List some sorting algorithm.


2 Marks Questions SQ–22 T (CC-Sem-3 & 4)

Ans.
1. Insertion sort
2. Selection sort
3. Bubble sort
4. Merge sort

5.12. What is binary search ?


Ans. Binary search is a search algorithm that finds the position of a
target value within a sorted list.

5.13. Which method is used to sort a list ?


Ans. Sort( ) method is used to sort a list.

5.14. What are the possibilities while sorting a list of string ?


Ans. Possibilities while sorting a list of string are :
1. Sorting in alphabetical/reverse order.
2. Based on length of string character.
3. Sorting the integer values in list of string.


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

Note : 1. Attempt all Section.


Section-A
1. Answer all questions in brief. (2 × 10 = 20)
a. What is the difference between list and tuples in Python ?

b. In some languages, every statement ends with a semi-colon


(;). What happens if you put a semi-colon at the end of a
Python statement ?

c. Mention five benefits of using Python.

d. How is Python an interpreted language ?

e. What type of language is python ?

f. What are local variables and global variables in Python ?

g. What is the difference between Python Arrays and lists ?

h. Define ADT interface.

i. Define floor division with example.

j. Differentiate fruitful functions and void functions.

Section-B

2. Answer any three of the following : (3 × 10 = 30)


a. Explain iterator. Write a program to demonstrate the
Tower of Hanoi using function.

b. Discuss function in Python with its parts and scope.


Explain with example. (Take simple calculator with add,
subtract, division and multiplication).
Solved Paper (2019-20) SP–2 T (CC-Sem-3 & 4)

c. Discuss ADT in Python. How to define ADT ? Write code for


a student information.

d. Explain all the conditional statement in Python using


small code example.

e. What is Python? How Python is interpreted? What are the


tools that help to find bugs or perform static analysis?
What are Python decorators?

Section-C

3. Answer any one part of the following : (1 × 10 = 10)


a. Write short notes with example : The programming cycle
for Python, elements of Python, type conversion in Python,
operator precedence, and Boolean expression.

b. How memory is managed in Python? Explain PEP 8. Write


a Python program to print even length words in a string.

4. Answer any one part of the following : (1 × 10 = 10)


a. Explain expression evaluation and float representation
with example. Write a Python program for how to check if
a given number is Fibonacci number.

b. Explain the purpose and working of loops. Discuss break


and continue with example. Write a Python program to
convert time from 12 hour to 24-hour format.

5. Answer any one part of the following : (10 × 1 = 10)


a. Explain higher order function with respect to lambda
expression. Write a Python code to count occurrences of
an element in a list.

b. Explain unpacking sequences, mutable sequences, and list


comprehension with example. Write a program to sort list
of dictionaries by values in Python – Using lambda
function.

6. Answer any one part of the following : (1 × 10 = 10)


a. 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.

b. Discuss exceptions and assertions in Python. How to


handle exceptions with try-finally ? Explain five built-in
exceptions with example.
Python Programming SP–3 T (CC-Sem-3 & 4)

7. Answer any one part of the following : (1 × 10 = 10)


a. Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.

b. Discuss sorting and merging. Explain different types of


sorting with example. Write a Python program for Sieve of
Eratosthenes.


Solved Paper (2019-20) SP–4 T (CC-Sem-3 & 4)

SOLUTION OF PAPER (2019-20)

Note : 1. Attempt all Section.


Section-A
1. Answer all questions in brief. (2 × 10 = 20)
a. What is the difference between list and tuples in Python ?
Ans.
S. No. List Tuples
1. Lists are mutable, i.e., they Tuples are immutable (they are
can be edited. lists that cannot be edited).
2. Lists are usually slower than Tuples are faster than lists.
tuples.
3. Syntax : Syntax :
list_ 1 = [10, ‘Quantum’, 20] tup_ 1 = (10, ‘Quantum’, 20)

b. In some languages, every statement ends with a semi-colon


(;). What happens if you put a semi-colon at the end of a
Python statement ?
Ans. Python allows semicolon to use as a line terminator. So no error
will occur if we put a semi-colon; at the end of python statement.

c. Mention five benefits of using Python.


Ans. Benefits of Python :
1. Python is easy to learn.
2. Most automation, data mining, and big data platforms depend on
Python. This is because it is the ideal language to work with for
general purpose tasks.
3. Python provides productive coding environment.
4. It supports extensive libraries.
5. Python uses different frameworks to simplify the development
process.

d. How is Python an interpreted language ?


Ans. Python is called an interpreted language because it goes through
an interpreter, which turns the Python code into the language
understood by processor of the computer.

e. What type of language is python ?


Ans. Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics.

f. What are local variables and global variables in Python ?


Python Programming SP–5 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.

g. What is the difference between Python Arrays and lists ?


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.

h. Define ADT interface.


Ans. ADT interface only define as what operations are to be performed
but not how these operations will be implemented. It does not
specify how data will be organized in memory and what algorithms
will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view.

i. Define floor division with example.


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
Solved Paper (2019-20) SP–6 T (CC-Sem-3 & 4)

j. Differentiate fruitful functions and void functions.


Ans. The main difference between void and fruitful function in python
is :
1. Void does not return any value
2. Fruitful function returns some value

Section-B

2. Answer any three of the following : (3 × 10 = 30)


a. Explain iterator. Write a program to demonstrate the
Tower of Hanoi using function.
Ans.
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.
Recursive Python function to solve Tower of Hanoi :
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n==1:
print “Move disk 1 from rod”,from_rod,“to rod”,to_rod
return
TowerOfHanoi(n – 1, from_rod, aux_rod, to_rod)
print “Move disk”,n,“from_rod”,from_rod,“to rod”,to_rod
TowerOfHanoi(n – 1, aux_rod, to_rod, from_rod)
n=4
TowerOfHanoi(n, \‘A\’, \‘C\’, \‘B\’)
# A, C, B are the name of rods
Python Programming SP–7 T (CC-Sem-3 & 4)

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

b. Discuss function in Python with its parts and scope.


Explain with example. (Take simple calculator with add,
subtract, division and multiplication).
Ans. Function :
1. Functions are self-contained programs that perform some particular
tasks.
2. Once a function is created by the programmer for a specific task,
this function can be called anytime to perform that task.
3. Each function is given a name, using which we call it. A function
may or may not return a value.
4. There are many built-in functions provided by Python such as dir
(), len ( ), abs ( ), etc.
5. Users can also build their own functions, which are called user-
defined functions.
Parts of function : Function is defined by “def” keyword following
by function name and parentheses.
Syntax of function definition : def function_name ( ) :
Syntax of functional call : function_name ( )
Solved Paper (2019-20) SP–8 T (CC-Sem-3 & 4)

For example :

def max (x, y) :

‘‘‘return maximum among x and y’’’

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.

Fig. 3. The LEGB scope.


5. The LEGB rule refers to local scope, enclosing scope, global scope,
and built-in scope.
6. Local scope extends for the body of a function and refers to anything
indented in the function definition.
7. Variables, including the parameter, that are defined in the body of
a function are local to that function and cannot be accessed outside
the function. They are local variables.
8. The enclosing scope refers to variables that are defined outside a
function definition.
9. If a function is defined within the scope of other variables, then
those variables are available inside the function definition. The
variables in the enclosing scope are available to statements within
a function.
For example : Simple calculator using python :
# This function adds two numbers
def add(x, y) :
return x + y
# This function subtracts two numbers
def subtract(x, y) :
return x – y
# This function multiplies two numbers
def multiply(x, y) :
Solved Paper (2019-20) SP–10 T (CC-Sem-3 & 4)

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. Discuss ADT in Python. How to define ADT ? Write code for


a student information.
Ans. ADT in python :
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.
Python Programming SP–11 T (CC-Sem-3 & 4)

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)

# Create a list to add Students


ls =[ ]
# an object of Student class
obj = Student(‘ ’, 0, 0, 0)
print(“\nOperations used, ”)
print(“\n1.Accept Student details\n2.Display Student Details\n”/
/“3.Search Details of a Student\n4.Delete Details of Student” /
/“\n5.Update Student Details\n6.Exit”)
ch = int(input(“Enter choice:”))
if(ch == 1):
obj.accept(“A”, 1, 100, 100)
obj.accept(“B”, 2, 90, 90)
obj.accept(“C”, 3, 80, 80)
elif(ch == 2):
print(“\n”)
print(“\nList of Students\n”)
for i in range(ls.__len__()):
obj.display(ls[i])
elif(ch == 3):
print(“\n Student Found,”)
s = obj.search(2)
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 !”)

d. Explain all the conditional statement in Python using


small code example.
Python Programming SP–13 T (CC-Sem-3 & 4)

Ans. Different types of conditional statement are :


1. If statement :
i. An if statement consists of a Boolean expression followed by
one or more statements.
ii. With an if clause, a condition is provided; if the condition is
true then the block of statement written in the if clause will be
executed, otherwise not.
Syntax :
If (Boolean expression) : Block of code #Set of statements to execute
if
the condition is true
For example :
var = 100
if ( var == 100 ) : print “value of expression is 100”
print “Good bye !”
Output :
value of expression is 100
Good bye!
2. If else statement :
i. An if statement can be followed by an optional else statement,
which executes when the Boolean expression is False.
ii. The else condition is used when we have to judge one statement
on the basis of other.
Syntax :
If (Boolean expression): Block of code #Set of statements to
execute if
condition is true
else : Block of code #Set of statements to execute if condition
is false
For example :
num = 5
if (num > 10) :
print (“Number is greater than 10”)
else :
print (“Number is less than 10”)
print (“This statement will always be executed”)
Output :
Number is less than 10.
3. Nested-if statement :
i. Nested-if statements are nested inside other if statements.
That is, a nested-if statement is the body of another if statement.
Solved Paper (2019-20) SP–14 T (CC-Sem-3 & 4)

ii. We use nested if statements when we need to check secondary


conditions only if the fist condition executes as true.
Syntax :
if test expression 1 :
# executes when condition 1 is true
body of if statement
if test expression 2 :
# executes when condition 2 is true
Body of nested-if
else :
body of nested-if :
else :
body of if-else statement
For example :
a = 20
if (a == 20) :
# First if statement
if (a < 25) :
print (“a is smaller than 25”)
else :
print (“a is greater than 25”)
else :
print (“a is not equal to 20”)
Output :
a is smaller than 25
4. Elif statement :
i. Elif stands for else if in Python.
ii. We use elif statements when we need to check multiple
conditions only if the given if condition executes as false.
For example :
a = 50
if (a == 29) :
print (“value of variable a is 20”)
elif (a == 30) :
print (“value of variable a is 30”)
elif (a == 40) :
print (“value of variable a is 40”)
else :
print (“value of variable a is greater than 40”)
Output :
value of variable a is greater than 40

e. What is Python ? How Python is interpreted ? What are


the tools that help to find bugs or perform static analysis ?
What are Python decorators ?
Python Programming SP–15 T (CC-Sem-3 & 4)

Ans. Python : Python is a high-level, interpreted, interactive and


object-oriented scripting language. It is a highly readable language.
Unlike other programming languages, Python provides an
interactive mode similar to that of a calculator.
Interpretation of Python :
1. An interpreter is a kind of program that executes other programs.
2. When we write Python programs, it converts source code written
by the developer into intermediate language which is again
translated into the machine language that is executed.
3. The python code we write is compiled into python bytecode, which
creates file with extension .pyc.
4. The bytecode compilation happened internally and almost
completely hidden from developer.
5. Compilation is simply a translation step, and byte code is a lower-
level, and platform-independent, representation of source code.
6. Each of the source statements is translated into a group of bytecode
instructions. This bytecode translation is performed to speed
execution. Bytecode can be run much quicker than the original
source code statements.
7. The .pyc file, created in compilation step, is then executed by
appropriate virtual machines.
8. The Virtual Machine iterates through bytecode instructions, one
by one, to carry out their operations.
9. The Virtual Machine is the runtime engine of Python and it is
always present as part of the Python system, and is the component
that actually runs the Python scripts.
10. It is the last step of Python interpreter.
Following tools are the static analysis tools that help to
find bugs in python :
1. Pychecker : Pychecker is an open source tool for static analysis
that detects the bugs from source code and warns about the style
and complexity of the bug.
2. Pylint :
a. Pylint is highly configurable and it acts like special programs
to control warnings and errors, it is an extensive configuration
file.
b. It is an open source tool for static code analysis and it looks
for programming errors and is used for coding standard.
c. It also integrates with Python IDEs such as Pycharm, Spyder,
Eclipse, and Jupyter.
Python decorators :
1. Decorators are very powerful and useful tool in Python since it
allows programmers to modify the behavior of function or class.
Solved Paper (2019-20) SP–16 T (CC-Sem-3 & 4)

2. Decorators allow us to wrap another function in order to extend


the behavior of wrapped function, without permanently modifying
it.
3. In decorators, functions are taken as the argument into another
function and then called inside the wrapper function.
4. Syntax :
@gfg_decorator
def hello_decorator():
print(“Gfg”)
5. gfg_decorator is a callable function, will add some code on the top
of some another callable function, hello_decorator function and
return the wrapper function.

Section-C

3. Answer any one part of the following : (1 × 10 = 10)


a. Write short notes with example : The programming cycle
for Python, elements of Python, type conversion in Python,
operator precedence, and Boolean expression.
Ans. Programming cycle for Python :
1. Python’s programming cycle is dramatically shorter than that of
traditional programming cycle.
2. In Python, there are no compile or link steps.
3. Python programs simply import modules at runtime and use the
objects they contain. Because of this, Python programs run
immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even
possible to change and reload parts of a running program without
stopping it at all.
5. Fig. 7 shows Python’s impact on the programming cycle.

Start the application


Start the application
Test behavior
Test behavior
Stop the application
Edit program code
Edit program code
(b) Python’s programming cycle
(a) Python’s programming cycle with module reloading
Fig. 7.
Python Programming SP–17 T (CC-Sem-3 & 4)

6. Since Python is interpreted, there is a rapid turnaround after


program changes. And because Python’s parser is embedded in
Python-based systems, it is easy to modify programs at runtime.
Elements of Python :
Data types :
i. The data stored in the memory can be of many types. For example,
a person’s name is stored as an alphabetic value and his address is
stored as an alphanumeric value.
ii. Python has six basic data types which are as follows :
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Numeric :
1. Numeric data can be broadly divided into integers and real numbers
(i.e., fractional numbers). Integers can be positive or negative.
2. The real numbers or fractional numbers are called, floating point
numbers in programming languages. Such floating point numbers
contain a decimal and a fractional part.
For example :
>>> num1 = 2 # integer number
>>>num2 = 2.5 # real number (float)
>>>num1
2 # Output
>>>num2
2.5 # Output
>>>
String :
1. Single quotes or double quotes are used to represent strings.
2. A string in Python can be a series or a sequence of alphabets,
numerals and special characters.
For example :
>>> sample_string = “Hello” # store string value
>>> sample_string # display string value
‘Hello’ # Output
Solved Paper (2019-20) SP–18 T (CC-Sem-3 & 4)

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)

2. In terms of programming language, Yes is similar to True and No


is similar to False.
3. This True and False data is known as Boolean data and the data
types which stores this Boolean data are known as Boolean data
types.
For example :
>>> a = True
>>> type (a)
<type ‘bool’>
Type conversion in Python :
1. The process of converting one data type into another data type is
known as type conversion.
2. There are mainly two types of type conversion methods in Python :
a. Implicit type conversion :
i. When the data type conversion takes place during
compilation or during the run time, then it called an
implicit data type conversion.
ii. Python handles the implicit data type conversion, so we
do not have to explicitly convert the data type into another
data type.
For example :
a=5
b = 5.5
sum = a + b
print (sum)
print (type (sum)) # type() is used to display the datatype
o f a variable
Output :
10.5
<class ‘float’>
iii. In the given example, we have taken two variables of
integer and float data types and added them.
iv. Further, we have declared another variable named ‘sum’
and stored the result of the addition in it.
v. When we checked the data type of the sum variable, we
can see that the data type of the sum variable has been
automatically converted into the float data type by the
Python compiler. This is called implicit type conversion.
b. Explicit type conversion:
i Explicit type conversion is also known as type casting.
Solved Paper (2019-20) SP–20 T (CC-Sem-3 & 4)

ii. Explicit type co nve rsio n take s place whe n the


programmer clearly and explicitly defines the variables
in the program.
For example :
# adding string and integer data types using explicit type
conversion
a = 100
b = “200”
result1 = a + b
b = int(b)
result2 = a + b
print (result2)
Output :
Traceback (most recent call last):
File “”, line 1, in
TypeError : unsupported operand type (s) for +: ‘int’ and
‘str’ 300
iii. In the given example, the variable a is of the number
data type and variable b is of the string data type.
iv. When we try to add these two integers and store the
value in a variable named result1, a TypeError occurs.
So, in order to perform this operation, we have to use
explicit type casting.
v. We have converted the variable b into integer type and
then added variable a and b. The sum is stored in the
variable named result2, and when printed it displays 300
as output.
Operator precedence :
1. When an expression has two or more operator, we need to identify
the correct sequence to evaluate these operators. This is because
result of the expression changes depending on the precedence.
For example : Consider a mathematical expression :
10 + 5 / 5
When the given expression is evaluated left to right, the final
answer becomes 3.
2. However, if the expression is evaluated right to left, the final
answer becomes 11. This shows that changing the sequence in
which the operators are evaluated in the given expression also
changes the solution.
3. Precedence is the condition that specifies the importance of each
operator relative to the other.
Python Programming SP–21 T (CC-Sem-3 & 4)

Table 1. Operator precedence from lower precedence to higher.


Operator Description
NOT, OR AND Logical operators
in , not in Membership operator
is, not is Identity operator
=, %=, /=, //=, –=, +=, *=, **== Assignment operators.
<>, ==, != Equality comparison operator
<=, <, >, >= Comparison operators
^, | Bitwise XOR and OR operator
& Bitwise AND operator
<<, >> Bitwise left shift and right shift
+, – Addition and subtraction
*, /, %, ?? Multiplication, Division, Modulus and
floor division
** Exponential operator

Boolean expression : A boolean expression may have only one of


two values : True or False.
For example : In the given example comparison operator (==) is
used which compares two operands and prints true if they are
equal otherwise print false :
>>> 5 == 5
True # Output
>>> 5 == 6
False # Output

b. How memory is managed in Python ? Explain PEP 8. Write


a Python program to print even length words in a string.
Ans. Memory management :
1. Memory management in Python involves a private heap containing
all Python objects and data structures.
2. The management of this private heap is ensured internally by the
Python memory manager.
3. The Python memory manager has different components which
deal with various dynamic storage management aspects, like
sharing, segmentation, preallocation or caching.
4. At the lowest level, a raw memory allocator ensures that there is
enough room in the private heap for storing all Python-related
Solved Paper (2019-20) SP–22 T (CC-Sem-3 & 4)

data by interacting with the memory manager of the operating


system.
5. On top of the raw memory allocator, several object-specific
allocators operate on the same heap and implement distinct
memory management policies adapted to the peculiarities of every
object type.
PEP 8 :
1. A PEP is a design document providing information to the Python
community, or describing a new feature for Python or its processes
or environment.
2. The PEP should provide a concise technical specification of the
feature.
3. PEP is actually an acronym that stands for Python Enhancement
Proposal.
4. PEP 8 is Python’s style guide. It is a set of rules for how to format
the Python code to maximize its readability.
5. A PEP is a design document providing information to the Python
community, or describing a new feature for Python or its processes
or environment.
Program to print even length words in a string :
def printWords(s) :
# split the string
s = s.split(‘ ’)
# iterate in words of string
for word in s:
# if length is even
if len(word)%2==0:
print(word)
# Driver Code
s = “i am muskan”
printWords(s)
Output :
am
muskan

4. Answer any one part of the following : (1 × 10 = 10)


a. Explain expression evaluation and float representation
with example. Write a Python program for how to check if
a given number is Fibonacci number.
Ans. Expression evaluation :
1. In Python actions are performed in two forms :
a. Expression evaluation,
b. Statement execution.
Python Programming SP–23 T (CC-Sem-3 & 4)

2. The key difference between these two forms is that expression


evaluation returns a value whereas statement execution does not
return any value.
3. A Python program contains one or more statements. A statement
contains zero or more expressions.
4. Python executes a statement by evaluating its expressions to values
one by one.
5. Python evaluates an expression by evaluating the sub-expressions
and substituting their values.
For example :
>>> program = “Hello Python”
>>> program
‘Hello Python’ #Output
>>> print program
Hello Python #Output
6. An expression is not always a mathematical expression in Python.
A value by itself is a simple expression, and so is a variable.
7. In the given example, we assigned a value “Hello Python” to the
variable program. Now, when we type only program, we get the
output ‘Hello Python’. This is the term we typed when we assigned
a value to the variable. When we use a print statement with program
it gives the value of the variable i.e., the value after removing
quotes.
Float representation :
1. Floating point representations vary from machine to machine.
2. The float type in Python represents the floating-point number.
3. Float is used to represent real numbers and is written with a decimal
point dividing the integer and fractional parts.
4. For example: 97.98, 32.3 + e18, – 32.54e100 all are floating point
numbers.
5. Python float values are represented as 64-bit double-precision
values.
6. The maximum value any floating-point number can be is approx
1.8 × 10308.
7. Any number greater than this will be indicated by the string inf in
Python.
8. Floating-point numbers are represented in computer hardware as
base 2 (binary) fractions.
9. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/
1000, and in the same way the binary fraction 0.001 has value
0/2 + 0/4 + 1/8.
Solved Paper (2019-20) SP–24 T (CC-Sem-3 & 4)

For example : # Python code to demonstrate float values.


Print(1.7e308)
# greater than 1.8 * 10^308
# will print ‘inf ’
print(1.82e308)
Output :
1.7e+308
inf
Program to check if a given number is Fibonacci number :
import math
# A utility function that returns true if x is perfect square
def isPerfectSquare(x):
s = int(math.sqrt(x))
return s*s == x
# Returns true if n is a Fibonacci number, else false
def isFibonacci(n):
return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n – 4)
# A utility function to test above functions
for i in range(1,6):
if (isFibonacci(i) == True):
print i,“is a Fibonacci Number”
else:
print i,“is a not Fibonacci Number”
Output :
1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is a not Fibonacci Number
5 is a Fibonacci Number

b. Explain the purpose and working of loops. Discuss break


and continue with example. Write a Python program to
convert time from 12 hour to 24-hour format.
Ans. Purpose and working of loops :
1. A loop is a programming structure that repeats a sequence of
instructions until a specific condition is met.
2. A loop statement allows us to execute a statement or group of
statements multiple times.
3. Python programming language provides following types of loops to
handle looping requirements:
a. For
b. While
c. Nested
4. Purpose : The purpose of loops is to repeat the same, or similar,
code a number of times. This number of times could be specified to
Python Programming SP–25 T (CC-Sem-3 & 4)

a certain number, or the number of times could be dictated by a


certain condition being met.
5. Working : Consider the flow chart for a loop execution :
Loop Entry

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)

5. Answer any one part of the following : (10 × 1 = 10)


a. Explain higher order function with respect to lambda
expression. Write a Python code to count occurrences of
an element in a list.
Ans.
1. Reduce(), filter(), map() are higher order functions used in Python.
2. Lambda definition does not include a “return” statement, it always
contains an expression which is returned.
3. We can also put a lambda definition anywhere a function is
expected, and we do not have to assign it to a variable at all.
4. Lambda functions can be used along with built-in higher order
functions like filter(), map() and reduce().
Use of lambda with filter() :
1. The filter() function in Python takes in a function and a list as
arguments.
2. This function helps to filter out all the elements of a sequence
“sequence”, for which the function returns true.
For example : Python program that returns the odd numbers
from an input list :
# Python code to illustrate filter() with lambda
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambdax: (x%2!=0), li))
print(final_list)
Output :
[5, 7, 97, 77, 23, 73, 61]
Use of lambda() with reduce() :
1. The reduce() function in Python takes in a function and a list as
argument.
2. The function is called with a lambda function and a list and a new
reduced result is returned. This performs a repetitive operation
over the pairs of the list.
3. This is a part of functools module.
For example :
# Python code to illustrate reduce() with lambda() to get sum of a
list from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y : x + y), li)
print (sum)
Output :
193
Solved Paper (2019-20) SP–28 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

b. Explain unpacking sequences, mutable sequences, and list


comprehension with example. Write a program to sort list
of dictionaries by values in Python – Using lambda
function.
Ans.
A. Unpacking sequences :
1. Unpacking allows to extract the components of the sequence
into individual variable.
2. Several diffe re nt assignments can be pe rforme d
simultaneously.
3. We have multiple assignments in Python where we can have
multiple LHS assigned from corresponding values at the RHS.
This is an example of unpacking sequence.
4. There is one restriction, the LHS and RHS must have equal
length. That is, every value that is created at RHS should be
assigned to LHS.
5. Strings and tuples are example of sequences. Operations
applicable on seque nces are : Inde xing, re pe tition,
concatenation.
For example :
>>> student
(‘Aditya’, 27, (‘Python’, ‘Abha’, 303))
>>> name, roll, regdcourse = student
>>> name
Output : Aditya
Python Programming SP–29 T (CC-Sem-3 & 4)

>>> 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)

5. Set builder notation is a notation is a mathematical notation


for describing a set by stating the property that its members
should satisfy. The syntax is
[<expression> for <element> in <sequence> if <conditional>]
The syntax is read as “Compute the expression for each element
in the sequence, if the conditional is true”.
For example :

>>> 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

5. In the given example, the output for both without list


comprehension and using list comprehension is the same.
6. The use of list comprehension requires lesser code and also
runs faster.
7. From above example we can say that list comprehension
contains :
a. An input sequence
b. A variable referencing the input sequence
c. An optional expression
d. An output expression or output variable
Program :
# Initializing list of dictionaries
lis = [{“name” : “Nandini”, “age” : 20},
{“name” : “Manjeet”, “age” : 20 },
{“name” : “Nikhil” , “age” : 19 }]
# using sorted and lambda to print list sorted by age
print “The list printed sorting by age :”
print sorted(lis, key = lambda i: i[‘age’])
print (“\r”)
# using sorted and lambda to print list sorted by both age and
name
print “The list printed sorting by age and name:”
print sorted(lis, key = lambda i: (i[‘age’], i[‘name’]))
print (“\r”)
# using sorted and lambda to print list sorted
# by age in descending order
Python Programming SP–31 T (CC-Sem-3 & 4)

print “The list printed sorting by age in descending order:”


print sorted(lis, key = lambda i: i[‘age’],reverse=True)
Output :
The list printed sorting by age:
[{‘age’: 19, ‘name’: ‘Nikhil’}, {‘age’: 20, ‘name’: ‘Nandini’}, {‘age’: 20,
‘name’: ‘Manjeet’}]
The list printed sorting by age and name :
[{‘age’: 19, ‘name’: ‘Nikhil’}, {‘age’: 20, ‘name’: ‘Manjeet’}, {‘age’: 20,
‘name’: ‘Nandini’}]
The list printed sorting by age in descending order:
[{‘age’: 20, ‘name’: ‘Nandini’}, {‘age’: 20, ‘name’: ‘Manjeet’}, {‘age’:
19, ‘name’: ‘Nikhil’}]

6. Answer any one part of the following : (1 × 10 = 10)


a. 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.
Ans. File I/O :
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.
A. Open a file :
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])
B. Read a file :
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.
Solved Paper (2019-20) SP–32 T (CC-Sem-3 & 4)

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])
C. Write into a file :
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’)
# clos the file after writing
>>> f.close ()
D. Close a file :
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 ()
Program to read a file line-by-line :
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’)
Python Programming SP–33 T (CC-Sem-3 & 4)

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

b. Discuss exceptions and assertions in Python. How to


handle exceptions with try-finally ? Explain five built-in
exceptions with example.
Ans. Exception :
1. While writing a program, we often end up making some errors.
There are many types of error that can occur in a program.
2. The error caused by writing an improper syntax is termed syntax
error or parsing error; these are also called compile time errors.
3. Errors can also occur at runtime and these runtime errors are
known as exceptions.
4. There are various types of runtime error in Python.
5. For example, when a file we try to open does not exist, we get a
FileNotFoundError. When a division by zero happens, we get a
ZeroDivisionError. When the module we are trying to import does
not exist, we get an ImportError.
6. Python creates an exception object for every occurrence of these
run-time errors.
7. The user must write a piece of code that can handle the error.
8. If it is not capable of handling the error, the program prints a trace
back to that error along with the details of why the error has
occurred.
Assertions :
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.
Solved Paper (2019-20) SP–34 T (CC-Sem-3 & 4)

5. The syntax for assert is : assert Expression [, Arguments]


6. If the assertion fails, Python uses ArgumentExpression as the
argument for the AssertionError.
Handle exceptions :
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.
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.
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
For example :
try:
a = [1, 2, 3]
print a[3]
except LookupError :
print “Index out of bound error.”
else:
print “Success”
2. TypeError : TypeError is thrown when an operation or function
is applied to an object of an inappropriate type.
Python Programming SP–35 T (CC-Sem-3 & 4)

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

7. Answer any one part of the following : (1 × 10 = 10)


a. Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.
Solved Paper (2019-20) SP–36 T (CC-Sem-3 & 4)

Ans.
Property Recursion Iteration

Definition Function calls itself. A set o f instructio n


repeatedly executed.
Application For functions. For loops.
Termination Through base case, When the te rmination
where there will be no condition for the iterator
function call. ceases to be satisfied.
Usage Used when code size Used when time
need to be small, and complexity needs to be
time complexity is not balanced against an
an issue. expanded code size.
Code size Smaller code size. Larger code size.
Time Very high (generally Relatively lower time
Complexity exponential) time complexity (generally
complexity. polynomial logarithmic).
Stack The stack is used to Does not use stack.
store the set of new
local variables and
parameters each time
the function is called.
Overhead Recursion possesses No overhead of repeated
the overhead of function call.
repeated function calls.
Speed Slow in execution. Fast in execution.

Program for recursive Fibonacci series :


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))
Python Programming SP–37 T (CC-Sem-3 & 4)

b. Discuss sorting and merging. Explain different types of


sorting with example. Write a Python program for Sieve of
Eratosthenes.
Ans. 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 :
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.
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)
2. Merge sort :
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.
Solved Paper (2019-20) SP–38 T (CC-Sem-3 & 4)

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)



You might also like