0% found this document useful (0 votes)
15 views61 pages

Python Paper Solution

The document contains a previous year's solved paper for Python programming at Dr. A. P. J. Abdul Kalam Technical University, covering various topics such as programming cycles, list slicing, module imports, and object-oriented programming. It includes sections with theoretical questions and practical programming tasks, along with examples and explanations. The paper is structured into multiple sections, each addressing different aspects of Python programming.

Uploaded by

anishakum17
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)
15 views61 pages

Python Paper Solution

The document contains a previous year's solved paper for Python programming at Dr. A. P. J. Abdul Kalam Technical University, covering various topics such as programming cycles, list slicing, module imports, and object-oriented programming. It includes sections with theoretical questions and practical programming tasks, along with examples and explanations. The paper is structured into multiple sections, each addressing different aspects of Python programming.

Uploaded by

anishakum17
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/ 61

lOMoARcPSD|56238245

y
Dr. A. P. J. Abdul Kalam Technical

em
University, Lucknow

PYTHON PROGRAMMING
ad
Ac
Previous Year Solved Paper
ity
es
iv
Un

(SEM III) THEORY EXAMINATION 2022-23


(SEM III) THEORY EXAMINATION 2021-22
(SEM IV) THEORY EXAMINATION 2021-22
(SEM III) THEORY EXAMINATION 2020-21

University Academy | 1

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Index

(SEM III) THEORY EXAMINATION 2022-23 5


(SEM III) THEORY EXAMINATION 2021-22 6
(SEM IV) THEORY EXAMINATION 2021-22 23
(SEM III) THEORY EXAMINATION 2020-21 38
51

y
em
ad
Ac
ity
es
iv
Un

University Academy | 2

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

(SEM III) THEORY EXAMINATION 2022-23


Note: Attempt all Sections. If you require any missing data, then choose suitably.
SECTION A 1x10=10
Attempt all questions in brief.
(a) Explain the Programming Cycle for Python in detail.
Python is an interpreted, high-level, general-purpose programming language. A python
programming cycle consists of below main steps.
1. Design a solution
2. Write a code
3. Test the code

y
4. Debug the code

em
5. Repeat 2-4 until the program runs correctly.

(b) Describe the concept of List Slicing with a suitable example.


list is a collection of items that are ordered and changeable. One of the most powerful

a list. ad
features of Python lists is slicing, which allows you to extract a subset of the elements from

Slicing a list is done using the syntax list[start:end:step], where start is the starting index of
Ac
the slice, end is the ending index (exclusive) of the slice, and step is the step size between
each element in the slice
example of using list slicing to extract a subset of elements from a list:
ity

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# get the first three elements
print(my_list[:3]) # [0, 1, 2]
# get the elements from index 3 to index 6 (exclusive)
es

print(my_list[3:6]) # [3, 4, 5]
# get every other element starting from index 1
print(my_list[1::2]) # [1, 3, 5, 7, 9]
iv

# get the last two elements


print(my_list[-2:]) # [8, 9]
Un

(c) Show the way to import the module in python


There are different ways to import a module in Python, but the most common ones are:
1. import statement: This statement is used to import a module into your Python
script.
import math # import the math module
print(math.pi) # access the pi constant defined in the math module
2. from ... import statement: This statement is used to import specific attributes,
functions, or classes from a module into your Python script.
from math import pi # import the pi constant from the math module
print(pi)

University Academy | 3

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

3. import ... as statement:This statement is used to import a module with an alias


name to avoid naming conflicts with other objects in your code.
import math as m # import the math module with an alias name 'm'
print(m.pi)
4. from ... import * statement: This statement is used to import all the attributes,
functions, or classes from a module into your Python script.
from math import * # import all attributes, functions, and classes
print(pi)

(d) Differentiate between Python Arrays and lists?


1. Data type: Arrays can only store elements of the same data type, while lists can store elements of

y
any data type.

em
2. Memory allocation: Arrays are allocated in contiguous memory locations, which makes them more
efficient for numerical operations. Lists are implemented as dynamic arrays that are dynamically
resized as needed, which can be time-consuming for large lists.
3. Size: Arrays have a fixed size, while lists are dynamic and can be resized at any time.
4.

5.
ad
Operations: Arrays have a smaller set of functions and methods than lists, but they have additional
operations that are optimized for numerical operations, such as slicing, indexing, broadcasting,
and vectorized operations. Lists have a wider range of built-in functions and methods.
Import: Arrays are implemented using the array module or the numpy library, which need to be
Ac
imported separately, while lists are built-in and do not require any external imports.

(e) Define floor division with an example.


floor division is a mathematical operation that returns the quotient of a division rounded
ity

down to the nearest integer. The floor division operator is represented by //. Here's an
Example:
>>> 15 // 2
es

7
>>> -15 // 2
iv

-8
(f) Explain the difference between 'append' and 'extend' in Python?
Un

Both append() and extend() are methods used in Python to add elements to a list. However,
they have some differences in terms of their functionality.
● append() is used to add a single element to the end of the list. It takes a single
argument, which can be any data type, and adds it to the end of the list. Here's an
example:
>>> my_list = [1, 2, 3]
>>> my_list.append(4)
>>> print(my_list)
[1, 2, 3, 4]

University Academy | 4

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

● extend() is used to add multiple elements to the end of the list. It takes an
iterable, such as a list or a tuple, and adds each element of the iterable to the end
of the list. Here's an example:
>>> my_list = [1, 2, 3]
>>> my_list.extend([4, 5, 6])
>>> print(my_list)
[1, 2, 3, 4, 5, 6]
(g) What is a dictionary in Python?
dictionary is a built-in data structure that represents a collection of key-value pairs.
Dictionaries are also known as associative arrays, maps, or hash tables in other

y
programming languages. In a dictionary, the keys must be unique, hashable, and immutable,
while the values can be of any data type and mutable.

em
Dictionaries are defined using curly braces {} and each key-value pair is separated by a
colon :. Here's an example:
>>> my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
>>> print(my_dict)
{'name': 'John', 'age': 30, 'city': 'New York'}

(h) What is object-oriented programming (OOP) in Python? Give an example.


ad
Ac
Object-oriented programming (OOP) is a programming paradigm that is based on the
objects that interact with one another.
concept of "objects", which can contain data and methods (functions) that act on that data.
ity

OOP allows for the creation of complex, reusable, and modular code by organising it into
In Python, everything is an object, including built-in data types such as integers, strings,
and lists. Python supports OOP through the use of classes, which are templates for creating
es

objects. A class defines the attributes (data) and methods (functions) that an object of that
class will have.
simple class in Python:
iv

class Car:
def __init__(self, make, model, year):
Un

self.make = make
self.model = model
self.year = year

def description(self):
return f"{self.year} {self.make} {self.model}"
#We can create an object of the Car
my_car = Car('Toyota', 'Corolla', 2022)
# Now we can access the attributes of the my_car object and call its methods:
print(my_car.make) # Output: Toyota
print(my_car.description()) # Output: 2022 Toyota Corolla

University Academy | 5

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

(i) What will be the output of the following python code


def count1(s):
vowels = "AEIOUaeiou"
count = 0
for c in s:
if c in vowels:
count += 1
return count
print(count1('I love India'))

y
The output of this code would be 6

em
j) What will be the output of the following code?
list1 = ['M', 'o', 'n', 'k', 'e', 'y']
print("@".join(list1))

Output: M@o@n@k@e@y
ad
Ac
SECTION B
Attempt any three of the following: 5x3=15
(a) Demonstrate five different built in functions used in the string. Write a program to check
whether a string is a palindrome or not.
ity

five different built-in functions used in Python strings:

1. len(): This function returns the length of a string, which is the number of characters in the
es

string. For example:


s = "hello"
print(len(s)) # Output: 5
iv

2. upper(): This function returns a new string with all the characters in the original string
converted to uppercase. For example:
Un

s = "hello"
print(s.upper()) # Output: HELLO
3. lower(): This function returns a new string with all the characters in the original string
converted to lowercase. For example:
s = "HELLO"
print(s.lower()) # Output: hello
4. replace(): This function returns a new string with all occurrences of a specified substring
replaced with another substring. For example:
s = "hello world"
print(s.replace("world", "Python")) # Output: hello Python

University Academy | 6

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

5. split(): This function splits a string into a list of substrings based on a specified delimiter.
For example:
s = "hello,world"
print(s.split(",")) # Output: ['hello', 'world']

Now, here's a program to check whether a string is a palindrome or not:


def is_palindrome(s):
# Convert the string to lowercase and remove whitespace
s = s.lower().replace(" ", "")
# Check if the string is equal to its reverse
return s == s[::-1]

y
# Test the function with some examples

em
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("Hello, world")) # Output: False
print(is_palindrome("A man a plan a canal Panama")) # Output: True

ad
(b) Explain the following loops with a flow diagram, syntax, and suitable examples
1. For Loop : The for loop is used to iterate over a sequence (such as a list, tuple, string, etc.)
and execute a block of code for each element in the sequence. Here is the syntax of a for
Ac
loop in Python:
for var in sequence:
statement(s)
Example
ity

py_list = ['Apple','Mango','Guava','Pineapple']
i = 1
#Iterating over the list
es

for item in py_list:


print ('Item ',i,' is ',item)
i = i+1
iv

Output:
Item 1 is Apple
Un

Item 2 is Mango
Item 3 is Guava
Item 4 is Pineapple

2. While loop: Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
Syntax
while(expression)
statement(s)
Example
n = 0

University Academy | 7

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

count = 0
while count < 5:
if n % 2 == 0:
print(n)
count += 1
n += 1
Output:
0
2
4
6

y
8

em
(c) Explain the continue, break, and pass statements with a suitable example.
In Python, continue, break, and pass are three statements used to alter the flow of control in loops
and conditional statements.

on to the next iteration.


Example:
ad
1. continue: The continue statement is used to skip the current iteration of a loop and move
Ac
for i in range(1, 11):
if i % 2 == 0:
continue # skip even numbers
print(i)
ity

Output :
1
3
es

5
7
9
iv

2. break: The break statement is used to exit a loop prematurely, even if the loop's condition
has not been met.
Un

Example
for i in range(1, 11):
if i == 5:
break # exit loop when i equals 5
print(i)
Output
1
2
3
4

University Academy | 8

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

3. pass: The pass statement is used as a placeholder when no action is required in a block of
code. It is typically used as a placeholder for code that has not yet been implemented.
Example:
for i in range(1, 11):
if i % 2 == 0:
pass # do nothing for even numbers
else:
print(i)
Output
Copy code

y
1
3

em
5
7
9

(d) Develop a program to calculate the reverse of any entered number. ad


Ac
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
remainder = num % 10
ity

reverse = (reverse * 10) + remainder


num = num // 10
print("The reverse of the entered number is:", reverse)
es

output
Enter a number: 12345
The reverse of the entered number is: 54321
iv

(e) Explain the list Comprehension with any suitable example.


Un

List comprehension is a concise and elegant way to create a new list from an existing one,
using a single line of code. It is a powerful and widely-used feature in Python.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
In this example, we have a list of numbers [1, 2, 3, 4, 5]. We want to create a new list that
contains the squares of these numbers. We could do this using a for loop like so:
numbers = [1, 2, 3, 4, 5]
squares = []
for x in numbers:
squares.append(x**2)

University Academy | 9

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

print(squares)
This would give us the same result as the list comprehension version. However, the list
comprehension is a more concise and readable way to achieve the same result.
The output of the program will be:
[1, 4, 9, 16, 25]

SECTION C 5x1-5
1. Attempt any one part of the following:
(a) Illustrate Unpacking Sequences, Mutable Sequences, and List comprehension with examples.
Unpacking Sequences:

y
1. Unpacking sequences is the process of assigning the values of a sequence (e.g., a tuple, list)
to multiple variables in a single statement. Here's an example:

em
t = (1, 2, 3)
a, b, c = t
print(a, b, c)
Output :
1 2 3
2. Mutable Sequences: ad
Ac
Mutable sequences are sequences (e.g., lists) that can be changed after they are created.
Here's an example of how to use a list, which is a mutable sequence, to add or remove
elements:
my_list = [1, 2, 3, 4]
ity

my_list.append(5) # add an element to the end of the list


print(my_list)
my_list.remove(2) # remove an element from the list
es

print(my_list)
Output
[1, 2, 3, 4, 5]
iv

[1, 3, 4, 5]
3. List Comprehension:
Un

List comprehension is a concise way to create a new list by applying a transformation to


each element of an existing list. Here's an example:
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
(b) Explain the lambda function. How it is helpful in the higher order function. Explain map()
function with a suitable example,
A lambda function is a small anonymous function in Python that can have any number of

University Academy | 10

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

arguments, but can only have one expression. Lambda functions are often used as a
shortcut to define functions that will only be used once in the code.
The syntax for a lambda function:
lambda arguments: expression
lambda function to add two numbers:
add = lambda x, y: x + y
print(add(2, 3))
Output:
5

y
The map() function is a built-in function in Python that applies a given function to each
element of an iterable (e.g., a list, tuple, etc.) and returns a new iterable with the results.

em
The syntax for the map() function is as follows:
map(function, iterable)
Example:
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) ad
Ac
Output:
[1, 4, 9, 16, 25]
This is a list containing the squares of the original numbers list [1, 2, 3, 4, 5]. The map()
function is often used in combination with lambda functions to perform operations on
ity

iterables in a concise way.

2. Attempt any one part of the following:


es

(a) Discuss the different types of argument-passing methods in python. Explain the variable
length argument with any suitable example
There are four types of argument-passing methods:
iv

1. Positional arguments: These are the default type of arguments in Python. The values are
assigned to the function parameters in the order they are passed.
Un

Example:
def sum(a, b, c):
return a + b + c

result = sum(1, 2, 3)
print(result)
Output:
6
2. Keyword arguments: These are arguments where we can explicitly pass a value to a
parameter by using its name.

University Academy | 11

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Example:
def greet(name, greeting):
return f"{greeting}, {name}!"
result = greet(name="John", greeting="Hello")
print(result)
Output:
"Hello, John!"
3. Default arguments: These are arguments where we can assign a default value to a
parameter. If no value is passed for that parameter, the default value is used.
Example:

y
def power(base, exponent=2):
return base ** exponent

em
result1 = power(2) # 2^2 = 4
result2 = power(2, 3) # 2^3 = 8
print(result1, result2)
Output:
4 8
ad
4. Variable-length arguments: These are arguments where we can pass a variable number
of arguments to a function. There are two types of variable-length arguments:
Ac
a. *args: This is used to pass a variable number of positional arguments to a function.
Example:
def add(*args):
ity

sum = 0
for arg in args:
sum += arg
es

return sum
result = add(1, 2, 3, 4, 5)
print(result)
iv

Output: 15
b. **kwargs: This is used to pass a variable number of keyword arguments to a function.
Un

Example:
def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

person_info(name="John", age=30, city="New York")


Output:
name: John
age: 30
city: New York

University Academy | 12

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Note: Variable-length arguments are useful when we don't know in advance how many
arguments we need to pass to a function. They give us the flexibility to pass any number of
arguments without having to define multiple parameters.

(b) Write short notes on the following with a suitable example


1) Encapsulation 2) Inheritance
1. Encapsulation:
Encapsulation is a fundamental concept of object-oriented programming that refers to the
idea of bundling data and methods that operate on that data within a single unit, called a
class. Encapsulation provides two key benefits: data hiding and code reuse. By hiding the

y
implementation details of a class, encapsulation allows us to protect the data from being
modified or accessed directly from outside the class. This helps to prevent bugs and

em
maintain code integrity. At the same time, encapsulation allows us to reuse code more
easily by creating objects that can be used in other parts of our code without worrying
about the underlying details.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
ad
Ac
def deposit(self, amount):
self.__balance += amount
ity

def withdraw(self, amount):


if amount > self.__balance:
raise ValueError("Insufficient balance!")
es

self.__balance -= amount

def get_balance(self):
iv

return self.__balance
account = BankAccount(1000)
account.deposit(500)
Un

account.withdraw(200)
print(account.get_balance())

Output: 1300
In this example, we have defined a BankAccount class with private attribute __balance
which cannot be accessed directly from outside the class. Instead, we have provided public
methods to deposit, withdraw and get the balance of the account.

University Academy | 13

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

2. Inheritance:
Inheritance is another fundamental concept of object-oriented programming that allows us
to create a new class by inheriting the properties and methods of an existing class. The
existing class is called the parent class or superclass, and the new class is called the child
class or subclass. Inheritance provides code reuse and allows us to create more specialized
classes based on a general template.
Example:
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age

y
def make_sound(self):

em
print("The animal makes a sound.")
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def make_sound(self):
print("The dog barks.")
dog = Dog("Buddy", 2, "Labrador")
ad
Ac
print(dog.name) # Output: "Buddy"
dog.make_sound()

Output: "The dog barks."


ity

In this example, we have defined an Animal class with a constructor that takes a name and
age parameter, and a method make_sound. We then create a Dog subclass that inherits from
es

the Animal class and adds a breed parameter to its constructor. We also override the
make_sound method to make the dog bark. Finally, we create a Dog object and call its
name and make_sound methods. The super() function is used to call the constructor of the
iv

parent class from within the child class.


Un

3. Attempt any one part of the following: 5x1-5


(a) Demonstrate the file handling procedure in detail. Write a python code to create a file with
P.txt' name and write your name and father's name in this file and then read this file to print it.

Python involves manipulating files on the computer's file system. The file can be opened, read,
written, and closed. Here's the file handling procedure in detail:
1. Opening a File:
To open a file in Python, you use the open() function. It requires a file path and a mode as
parameters. The mode tells Python what you want to do with the file. For example, 'r'
means you want to read the file, 'w' means you want to write to the file, and 'a' means you

University Academy | 14

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

want to append to the file.


2. Reading from a File:
After you open the file in read mode, you can read the contents of the file using the read()
or readline() methods.
3. Writing to a File:
After you open the file in write mode, you can write to the file using the write() method.
4. Closing a File:
After you're done working with a file, you should close it using the close() method.

Here's an example code to create a file named 'P.txt', write your name and father's name,

y
and then read the file to print it:

em
# Writing to a file
with open('P.txt', 'w') as file:
file.write('Name: John Doe\n')
file.write('Father\'s Name: Mike Doe\n')

# Reading from a file ad


Ac
with open('P.txt', 'r') as file:
content = file.read()
print(content)
Output:
ity

Name: John Doe


Father's Name: Mike Doe
es

(b) Demonstrate the Sieve of Eratosthenes theorem and write the python function to print
prime numbers between 1 to 100
The Sieve of Eratosthenes is an algorithm for finding all the prime numbers up to a given
iv

limit. It works by iteratively marking as composite (i.e., not prime) the multiples of each
prime, starting with the multiples of 2.
Un

Here's the step-by-step process of the Sieve of Eratosthenes algorithm:


Suppose we want to find all prime numbers up to 30 using the Sieve of Eratosthenes
algorithm.
1. First, we create a list of numbers from 2 to 30: [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].
2. We start with the first prime number, 2, and mark all its multiples as composite. So, we
mark 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, and 30 as composite.
3. Next, we move to the next unmarked number, which is 3, and mark all its multiples as
composite. So, we mark 6, 9, 12, 15, 18, 21, 24, 27, and 30 as composite.

University Academy | 15

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

4. We move to the next unmarked number, which is 5, and mark all its multiples as composite.
So, we mark 10, 15, 20, 25, and 30 as composite.
5. We move to the next unmarked number, which is 7, and mark all its multiples as composite.
However, there are no multiples of 7 left to mark as they have already been marked in the
previous steps.
6. We have now marked all composite numbers up to 30. The remaining unmarked numbers
are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29, which are all prime.
Therefore, the prime numbers up to 30 are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].
def sieve_of_eratosthenes(n):
primes = [True] * (n + 1)

y
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):

em
if primes[i]:
for j in range(i * i, n + 1, i):
primes[j] = False
for i in range(2, n + 1):
if primes[i]:
print(i) ad
Ac
sieve_of_eratosthenes(30)

Output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29


ity

4. Attempt any one part of the following:


(a) Develop and write the python code of selection sort to sort 41,65,43,91,12.14,62 elements.
Also, explain its complexity.
es

The Selection Sort algorithm sorts an array by repeatedly finding the minimum element from the
unsorted part and putting it at the beginning. In other words, we find the minimum element from
the unsorted part and swap it with the first element.
iv

Python code for Selection Sort to sort the given list of elements:
def selection_sort(arr):
Un

n = len(arr)
for i in range(n):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, n):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# Example usage
arr = [41,65,43,91,12,14,62]

University Academy | 16

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

print("Original array:", arr)


sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)

Output:
Original array: [41, 65, 43, 91, 12, 14, 62]
Sorted array: [12, 14, 41, 43, 62, 65, 91]
(b) Explain Binary search with its python code and complexity.
Binary search is a searching algorithm that works on sorted arrays/lists. It repeatedly
divides the search interval in half until the target value is found or the search interval is
Empty.

y
Here is the Python code for Binary Search:

em
def binary_search(arr, low, high, target):
if high >= low:
mid = (high + low) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:

ad
return binary_search(arr, low, mid-1, target)
else:
Ac
return binary_search(arr, mid+1, high, target)
else:
return -1
arr = [2, 3, 4, 10, 40]
ity

target = 10
result = binary_search(arr, 0, len(arr)-1, target)
if result != -1:
print("Element is present at index", result)
es

else:
print("Element is not present in array")
iv

Output :
Element is present at index 3
Un

5. Attempt any one part of the following: 5x1-5

(a) Explain the importance of Exception handling in any object-oriented programming language.
Explain try exceptions and finally block with any suitable example.
Exception handling is a crucial aspect of any programming language, including
object-oriented programming languages such as Python. Exception handling enables a
program to deal with unexpected errors or events that may occur during the execution of
the program. Without proper exception handling, these errors could cause the program to
crash, potentially leading to data loss or other undesirable consequences.

University Academy | 17

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

In Python, the try-except-finally block is used for exception handling. The try block contains
the code that is potentially risky and may throw an exception. The except block catches the
exception and handles it, preventing the program from crashing. The finally block contains
code that should be executed regardless of whether an exception was thrown or not. This
can be useful for performing cleanup tasks, such as closing files or network connections.
Here is an example of the try-except-finally block in Python:
try:
x = int(input("Enter a number: "))
y = 1 / x
except ValueError:

y
print("Invalid input. Please enter a number.")

em
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("The reciprocal of", x, "is", y)
finally:
print("Done.")
Output :
Enter a number: 0
ad
Ac
Cannot divide by zero.
Done.
Enter a number: A
ity

Invalid input. Please enter a number.


Done.

(b) Summarize the Tower of Hanoi puzzle and write its recursive function to implement it.
es

The Tower of Hanoi is a mathematical puzzle consisting of three rods and a number of disks
of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat
iv

stack in ascending order of size on one rod, the smallest at the top, thus making a conical
shape. The objective of the puzzle is to move the entire stack to another rod, obeying the
Un

following simple rules:


1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack or on an empty rod.
3. No disk may be placed on top of a smaller disk.
Recursive function to solve the Tower of Hanoi problem:
def tower_of_hanoi(n, from_rod, to_rod, aux_rod):
if n == 1:
print("Move disk 1 from rod", from_rod, "to rod", to_rod)
return
tower_of_hanoi(n-1, from_rod, aux_rod, to_rod)

University Academy | 18

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

print("Move disk", n, "from rod", from_rod, "to rod", to_rod)


tower_of_hanoi(n-1, aux_rod, to_rod, from_rod)

# Example usage:
tower_of_hanoi(3, 'A', 'C', 'B')

Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A

y
Move disk 2 from B to C

em
Move disk 1 from A to C

ad
Ac
ity
es
iv
Un

University Academy | 19

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

(SEM III) THEORY EXAMINATION 2021-22

SECTION A

1. Attempt all questions in brief. 2*5 = 10


a. Explain the Programming Cycle for Python in detail
Python is an interpreted, high-level, general-purpose programming language. A python
programming cycle consists of below main steps.
1. Design a solution

y
2. Write a code
3. Test the code

em
4. Debug the code
5. Repeat 2-4 until the program runs correctly.
b. What will be the output of the following Python code?
i=0
while i< 3:
print(i) ad
Ac
i += 1
else:
print(0)
The given code will produce the following output:
ity

c. What will be the output of the following Python code?


def cube(x):
return x * x * x
es

x = cube(3)
print x
The given code will produce the following output:
iv

d. How do we define an Interface for an ADT?


Un

The abstract data type is special kind of data type, whose behavior is defined by a set of
values and set of operations. The keyword “Abstract” is used as we can use these data
types, we can perform different operations. But how those operations are working that is
totally hidden from the user. The ADT is made of primitive data types, but operation logics
are hidden.
Some examples of ADT are Stack, Queue, List etc.
e. How do you perform a search in Python?
In Python, there are several ways to perform a search, depending on the type of data and
the specific requirements of the search algorithm. Here are some common search
algorithms and how to implement them in Python:

University Academy | 20

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

i. Linear search
ii. Binary search
iii. Depth-first search (DFS)
iv. Breadth-first search (BFS)

SECTION B

2. Attempt any three of the following: 5*3=15

a. What do you mean by Python IDE? Explain in detail.

y
Python IDE (Integrated Development Environment) is a software application that provides an

em
integrated environment for developing, debugging, and executing Python code. An IDE
typically includes a text editor, a debugger, and other tools to simplify and streamline the
development process.
Some of the key features of a Python IDE are:

ad
Text editor: The text editor is the main component of the IDE, and it provides a
graphical user interface for creating, editing, and saving Python code. The text
editor may include features such as syntax highlighting, auto-completion, and code
Ac
folding to make the development process faster and more efficient.

● Debugging tools: A Python IDE typically includes a debugger, which is used to find
and fix errors in the code. The debugger allows the developer to set breakpoints,
ity

step through the code line by line, and inspect variables and data structures at each
step to identify the source of the error.
es

● Code analysis: Many Python IDEs also include code analysis tools, such as linters and
code formatters, which help ensure that the code is written in a consistent and
iv

error-free way. Code analysis tools can detect potential errors, stylistic issues, and
other problems that may affect the performance or readability of the code.
Un

● Integration with other tools: A Python IDE may also include features that integrate
with other tools and technologies used in Python development, such as version
control systems like Git, package managers like Pip, and cloud platforms like AWS.

Examples of popular Python IDEs include PyCharm, Visual Studio Code with Python
extension, Spyder, IDLE, and Jupyter Notebook.

In summary, a Python IDE is a software application that provides an integrated environment


for developing, debugging, and executing Python code. It includes a text editor, a debugger,
and other tools to make the development process faster, more efficient, and error-free.

University Academy | 21

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

b. How can you randomize the items of a list in place in Python?


In Python, you can use the random module to shuffle the items of a list in place. Here's an
example:

import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

y
In the code above, random.shuffle() takes a list as an argument and shuffles the items
randomly in place. The original list is modified, and the new order of the items is not

em
predictable.

Note that the shuffle() method does not return a new shuffled list, it shuffles the list in

ad
place. Therefore, there is no need to assign the result of the shuffle() method to a new
variable.
Ac
c. Explain Tuples and Unpacking Sequences in Python Data Structure.

Tuples are an immutable data structure in Python that contain a sequence of values. Tuples
are similar to lists, but unlike lists, they cannot be modified once they are created. Tuples
ity

are defined using parentheses, and the values in a tuple are separated by commas.

Here's an example of a tuple:


es

my_tuple = (1, 2, 3, "four", 5.0)


iv

In Python, you can use unpacking to assign the values in a tuple or other sequence to
multiple variables. Unpacking sequences is a convenient way to assign the values of a
Un

sequence to multiple variables at once. To unpack a sequence, you simply assign the
sequence to a comma-separated list of variables.

Here's an example of unpacking a tuple:

my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3

University Academy | 22

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

In the code above, the variables a, b, and c are assigned the values of the tuple my_tuple.
The values are unpacked in the order they appear in the tuple.

You can also use the * operator to assign multiple values from a tuple to a single variable.
The * operator is called the "splat" operator in Python, and it allows you to capture any
remaining values in a sequence.
Here's an example of using the * operator to capture remaining values in a tuple:

my_tuple = (1, 2, 3, 4, 5)

y
a, b, *c = my_tuple
print(a) # Output: 1

em
print(b) # Output: 2
print(c) # Output: [3, 4, 5]

ad
In the code above, the variables a and b are assigned the first two values of the tuple, and
the remaining values are assigned to the variable c. The * operator captures any remaining
values in the sequence and assigns them to a list.
Ac
d. What are File input and output operations in Python Programming?
File input and output (I/O) operations in Python refer to the process of reading data from
and writing data to files. Python provides built-in functions for performing file I/O
ity

operations.

To open a file in Python, you use the open() function. The open() function takes two
es

arguments: the path to the file and the mode in which the file should be opened. The mode
can be one of several options, including:
iv

● 'r': Read mode. The file is opened for reading (default).


● 'w': Write mode. The file is opened for writing. If the file already exists, its contents
Un

are truncated. If the file does not exist, a new file is created.
● 'a': Append mode. The file is opened for writing, but new data is added to the end
of the file instead of overwriting existing data.
● 'x': Exclusive mode. The file is opened for writing, but only if it does not already
exist. If the file already exists, the open() function will raise an error.
Here's an example of opening a file in write mode and writing data to it:

# Open file for writing


f = open('example.txt', 'w')
# Write data to file

University Academy | 23

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

f.write('Hello, world!')

# Close file
f.close()
In the code above, the open() function is used to open a file named example.txt in write
mode. The write() method is then called on the file object to write the string 'Hello, world!'
to the file. Finally, the close() method is called on the file object to close the file.

To read data from a file, you can use the read() method on a file object. Here's an example:
# Open file for reading

y
f = open('example.txt', 'r')
# Read data from file

em
data = f.read()

# Close file
f.close()
# Print data
print(data) ad
In the code above, the open() function is used to open the file example.txt in read mode.
Ac
The read() method is then called on the file object to read the contents of the file into a
string variable named data. Finally, the close() method is called on the file object to close
the file.
ity

Python also provides several other file I/O functions and methods, including readline(),
readlines(), writelines(), and more. By using these functions and methods, you can read and
es

write data to files in a variety of ways.

e. Solve the Tower of Hanoi problem for n= 3 disk and show all the steps.
iv

The Tower of Hanoi is a classic problem in computer science and mathematics. The problem
involves moving a tower of disks from one peg to another, following three simple rules:
Un

Only one disk can be moved at a time.


A larger disk cannot be placed on top of a smaller disk.
The tower must be moved from the starting peg to the target peg.
For n disks, the problem can be solved in 2^n - 1 moves.

Here's an example solution for n=3 disks:


Start with all three disks on the first peg (source).
Move the top two disks from the first peg to the second peg (auxiliary) using the third peg
(target):
Move disk 1 from source to auxiliary

University Academy | 24

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Move disk 2 from source to target


Move disk 1 from auxiliary to target
Move the bottom disk from the first peg to the third peg (target).
Move disk 3 from source to target
Move the top two disks from the second peg (auxiliary) to the third peg (target) using the
first peg (source):
Move disk 1 from target to source
Move disk 2 from target to auxiliary
Move disk 1 from source to auxiliary
Move the bottom disk from the third peg (target) to the first peg (source):

y
Move disk 3 from target to source
Move the top two disks from the second peg (auxiliary) to the first peg (source) using the

em
third peg (target):
Move disk 1 from auxiliary to target
Move disk 2 from auxiliary to source
Move disk 1 from target to source

ad
At this point, all three disks are on the first peg (source), but in the correct order. The
tower has been successfully moved from the starting peg to the target peg in a total of 7
Ac
moves.

Python implementation of the Tower of Hanoi problem for n=3 disks:


def tower_of_hanoi(n, source, auxiliary, target):
ity

if n == 1:
print(f"Move disk {n} from {source} to {target}")
else:
es

tower_of_hanoi(n-1, source, target, auxiliary)


print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n-1, auxiliary, source, target)
iv

# Example usage
Un

tower_of_hanoi(3, 'A', 'B', 'C')

In the code above, the tower_of_hanoi() function takes four arguments:


● n: The number of disks to move.
● source: The name of the starting peg.
● auxiliary: The name of the auxiliary peg.
● target: The name of the target peg.
When we call tower_of_hanoi(3, 'A', 'B', 'C'), the function will output the following steps:
Move disk 1 from A to C
Move disk 2 from A to B

University Academy | 25

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Move disk 1 from C to B


Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

SECTION C

3. Attempt any one part of the following 5*1=5

y
em
a. Write a program in Python to execute the Selection sort algorithm
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.

ad
2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum
element (considering ascending order) from the unsorted subarray is picked and moved to
Ac
the sorted subarray.

Selection Sort algorithm in Python:


def selection_sort(arr):
ity

n = len(arr)
for i in range(n):
# Find the minimum element in the remaining unsorted array
es

min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
iv

min_idx = j

# Swap the found minimum element with the first element


Un

arr[i], arr[min_idx] = arr[min_idx], arr[i]

return arr

Here's an example usage of this function:


arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)

This would output:


Sorted array: [11, 12, 22, 25, 64]

University Academy | 26

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

b. Explain why python is considered an interpreted language.


Python is considered an interpreted language because it executes code directly without
requiring it to be compiled beforehand. When you write code in Python, you do not have to
compile it into a machine-readable format. Instead, the Python interpreter reads your code
and executes it line-by-line. This allows you to quickly test and run code without having to
go through a lengthy compilation process. However, because the interpreter has to translate
each line of code into machine code at runtime, interpreted code can be slower than
compiled code.

y
When you run a Python program, the code is first parsed by the Python interpreter, which
checks the syntax for errors and translates the source code into byte code, which is a

em
lower-level representation of the code. The byte code is then executed by the Python
virtual machine, which converts it into machine code instructions that the computer can
understand and execute.

ad
The process of interpreting Python code allows for greater flexibility and ease of use
compared to compiled languages. For example, in Python, you can interactively test code
Ac
snippets and quickly see the results, without having to compile and run a separate program.
Additionally, Python can be run on multiple platforms without having to recompile the code
for each platform, making it more portable.
ity

However, interpreting code can be slower than compiling it, as the interpreter has to
translate each line of code into machine code at runtime. To mitigate this, Python includes
features like just-in-time (JIT) compilation and caching of byte code, which can improve
es

performance.
iv
Un

University Academy | 27

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

4. Attempt any one part of the following 5*1=5


a. Write a Python program to construct the following pattern, using a
nested for loop.
*
**
***
****
*****
****
***

y
**

em
*

n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')

for i in range(n,0,-1):
ad
Ac
for j in range(i):
print('* ', end="")
print('')
ity

Output Flowchart
*
**
***
es

****
*****
****
iv

***
**
*
Un

b. Write a program to produce Fibonacci series in Python

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

University Academy | 28

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two
terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
# Function to generate Fibonacci sequence
def fibonacci(n):
if n <= 0:
print("Invalid input! Please enter a positive integer.")
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:

y
fib_seq = [0, 1]
for i in range(2, n):

em
next_fib = fib_seq[i-1] + fib_seq[i-2]
fib_seq.append(next_fib)
return fib_seq

# Example usage
n = 10
fib_seq = fibonacci(n) ad
Ac
print(fib_seq)

Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
ity

5. Attempt any one part of the following 5*1=5


es

a. Write a Python program to change a given string to a new string where the first and last
chars have been exchanged.
iv
Un

def change_sring(str1):
return str1[-1:] + str1[1:-1] + str1[:1]

print(change_sring('abcd'))
print(change_sring('12345'))

Sample Output:
dbca

University Academy | 29

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

52341

b. Write a Python program to add an item in a tuple.


#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an
element and it will create a new tuple

y
tuplex = tuplex + (9,)
print(tuplex)

em
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
ad
Ac
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
ity

Sample Output:
es

(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
iv

(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)


Un

6. Attempt any one part of the following 5*1=5

a. How to create and import a module in Python?


A module is simply a Python file with a .py extension that can be imported inside another
Python program. The name of the Python file becomes the module name. The module
contains definitions and implementation of classes, variables, and functions that can be
used inside another program.
Example: Let’s create a simple module named University.

University Academy | 30

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

# Defining a function
def UA():
print("UniversityAcademy")

# Defining a variable
location = "Noida"

name of the above Python file is University.py


import ‘University’ module using the import statement.
import University
University.UA()
# Print the variable declared

y
print(University.location)

em
Output:
UniversityAcademy
Noida

ad
b. Explain the algorithm Sieve of Eratosthene used in Python Programming.
Ac
The Sieve of Eratosthenes is an algorithm used to find all the prime numbers up to a given
limit. Here's how the algorithm works:
ity

● Create a list of consecutive integers from 2 through n: 2, 3, 4, ..., n.


● Initially, let p equal 2, the smallest prime number.
● Starting from p, enumerate its multiples by counting to n in increments of p, and
es

mark them in the list (these will be 2*p, 3*p, 4*p, ...; the p itself should not be
marked).
● Find the smallest number in the list greater than p that is not marked. If there was
iv

no such number, stop. Otherwise, let p now equal this new number (which is the
next prime), and repeat from step 3.
Un

● When the algorithm terminates, the numbers remaining not marked in the list are
all the primes below n.

Here's an example implementation of the Sieve of Eratosthenes in Python:

def sieve_of_eratosthenes(n):
primes = [True] * (n+1)
primes[0] = primes[1] = False

for p in range(2, int(n**0.5)+1):

University Academy | 31

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

if primes[p]:
for i in range(p**2, n+1, p):
primes[i] = False
return [p for p in range(2, n+1) if primes[p]]
This implementation uses a list of booleans to keep track of whether each number is prime
or not. Initially, all numbers are marked as prime. Then, for each prime number p, its
multiples are marked as composite. Finally, the remaining numbers that are still marked as
prime are returned as a list of primes.

7. Attempt any one part of the following 5*1=5

y
a. Write a Recursive function in python BinarySearch(Arr,l,R,X) to search the given

em
element X to be searched from the List Arr having R elements, where l represents
lower bound and R represents the upperbound.
def binary_search(arr, l, r, x):
if l > r:
return -1
mid = (l + r) // 2
if arr[mid] == x:
ad
Ac
return mid
elif arr[mid] > x:
return binary_search(arr, l, mid - 1, x)
ity

else:
return binary_search(arr, mid + 1, r, x)
es

This function takes four arguments:


arr: The list to search
l: The lower bound of the sublist to search (initially set to 0)
iv

r: The upper bound of the sublist to search (initially set to the length of the list
minus one)
Un

x: The element to search for


The function first checks if the lower bound l exceeds the upper bound r, which indicates
that the sublist is empty and the target element is not in the list. If this is the case, the
function returns -1 to indicate that the element was not found.

If the sublist is not empty, the function calculates the middle index of the sublist using
integer division (//). If the middle element is equal to the target, the function returns its
index.

University Academy | 32

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

If the middle element is greater than the target, the function recursively searches the left
half of the sublist by calling binary_search with the same list, the same lower bound l, and
the middle index minus one as the new upper bound r.

If the middle element is less than the target, the function recursively searches the right
half of the sublist by calling binary_search with the same list, the middle index plus one as
the new lower bound l, and the same upper bound r.

b. Explain the terms Merge List and Merge Sort in Python Programming
1. Merge List

y
A merge list is a list that is obtained by merging two or more sorted lists into a single sorted
list. The merge operation is a fundamental operation used in many algorithms such as

em
merge sort and the merge step in merge sort. In Python programming, there are several
ways to merge lists, including using the built-in sorted() function or using custom merge
functions.
Here is an example of how to merge two sorted lists in Python:
def merge_lists(list1, list2):
merged_list = [] ad
Ac
i = j = 0

while i < len(list1) and j < len(list2):


if list1[i] < list2[j]:
ity

merged_list.append(list1[i])
i += 1
else:
es

merged_list.append(list2[j])
j += 1
merged_list += list1[i:]
iv

merged_list += list2[j:]
return merged_list
Un

This function takes two sorted lists list1 and list2, and returns a new list that contains all
the elements from list1 and list2, sorted in ascending order.
2. Merge Sort
Merge sort is a sorting algorithm that uses the divide-and-conquer approach to sort a list of
elements. It works by dividing the list into two halves, sorting each half recursively using
merge sort, and then merging the sorted halves back into a single sorted list using the
merge operation. The merge sort algorithm has a time complexity of O(n log n), which
makes it more efficient than many other sorting algorithms.

Here is an example implementation of merge sort in Python:

University Academy | 33

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]

left = merge_sort(left)
right = merge_sort(right)

y
return merge_lists(left, right)

em
This function takes a list arr and recursively splits it into halves until the length of each
sublist is one or less. Then, it uses the merge_lists function described earlier to merge the
sorted sublists back into a single sorted list.

ad
Ac
ity
es
iv
Un

University Academy | 34

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

(SEM IV) THEORY EXAMINATION 2021-22

SECTION A

1. Attempt all questions in brief. 2.5*4 = 10


a. Discuss why Python is called a dynamic and strongly typed language?
Python is called a dynamic and strongly typed language because of the way it handles data
types during program execution.
● Dynamic Typing

y
Python is a dynamically typed language, which means that the type of a variable is
determined at runtime, not at compile time. In other words, the data type of a variable can

em
change during the execution of a program. For example, a variable can be assigned an
integer value, and then later be assigned a string value. This flexibility can be useful, as it
allows programmers to write code more quickly and easily without worrying about
specifying data types.

● Strong Typing
ad
Ac
Python is also a strongly typed language, which means that the type of a variable is
enforced by the language, and the interpreter will not automatically convert one type of
data into another. For example, if you try to add an integer and a string, you will get a
TypeError, because Python cannot automatically convert the string to an integer. This makes
ity

Python less error-prone than weakly typed languages, as it prevents unintended type
conversions.
es

x = 42
print(type(x)) # Output: <class 'int'>
iv

x = "Hello, world!"
print(type(x)) # Output: <class 'str'>
Un

y = "42"
z = x + y # Raises TypeError: can only concatenate str (not "int")
to str

In this example, the variable x is initially assigned an integer value, and its type is
determined to be int. Later, x is assigned a string value, and its type changes to str. The
variable y is assigned a string value, and the variable z is assigned the result of
concatenating x and y. However, because x is a string and y is a string, Python performs

University Academy | 35

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

string concatenation, which results in a TypeError when the interpreter tries to concatenate
x (which is a string) and 42 (which is an integer).

In summary, Python is a dynamic and strongly typed language because it allows data types
to change during program execution, but also enforces strict rules for type conversions to
prevent unintended errors.

b. How pass statement is different from a comment?


In Python, the pass statement and a comment are both used to indicate that a section of
code should be ignored by the interpreter, but they have different purposes.

y
● Pass statement

em
The pass statement is a placeholder statement in Python that does nothing. It is used when
a statement is required by the syntax, but you don't want to execute any code. For
example, it can be used as a placeholder in a function or a loop that has not been

to avoid syntax errors.


def my_function():
ad
implemented yet. The pass statement does not affect the program execution, but it is used
Ac
pass # This function does nothing yet, but it will not raise a
syntax error
In this example, the my_function function does not have any code inside it yet, but we use
the pass statement as a placeholder so that the interpreter does not raise a syntax error.
ity

● Comment
A comment in Python is a piece of text that is ignored by the interpreter. It is used to
provide information about the code or to disable a section of code temporarily. Comments
es

start with the # symbol and continue until the end of the line. Comments can also be
enclosed in triple quotes (''' or """) to span multiple lines.
iv

# This is a comment. It is ignored by the interpreter.


x = 42 # This is a comment. It explains what this line of code does.
Un

"""
This is a multiline comment.
It is enclosed in triple quotes.
"""
# The following line of code is temporarily disabled with a comment:
# print("This line of code is disabled")

In this example, we use comments to provide information about the code and to disable a
line of code temporarily.

University Academy | 36

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

SECTION B

2. Attempt any two of the following: 4*2 = 8


a. Write a python function named ComputeAverage to find average of a list of
numbers. It should handle the exception if the list is empty and return 0 in
that case.
Python function named ComputeAverage that finds the average of a list of numbers and
returns 0 if the list is empty:

def ComputeAverage(numbers):

y
try:

em
avg = sum(numbers) / len(numbers)
return avg
except ZeroDivisionError:
return 0

ad
In this function, we use a try-except block to handle the ZeroDivisionError exception that
may occur if the input list is empty. If the input list is not empty, we calculate the average
Ac
of the numbers using the sum and len functions, and return the result. If the input list is
empty, we catch the ZeroDivisionError exception and return 0.
Here's an example of how to use the ComputeAverage function:
ity

numbers = [2, 4, 6, 8, 10]


avg = ComputeAverage(numbers)
print(avg) # Output: 6.0
es

numbers = []
avg = ComputeAverage(numbers)
print(avg) # Output: 0
iv

b. Implement the binary search technique.


Refer Page: 17
Un

c. Explain the use of break and continue with a suitable example


break and continue are control flow statements that are used to alter the flow of a loop.

● Break statement:
The break statement is used to terminate a loop prematurely. When a break statement is
encountered inside a loop, the loop is immediately exited, and the control is transferred to
the statement immediately following the loop. This is useful when you want to exit a loop
when a certain condition is met.
Here is an example of using the break statement:
# Find the first even number in a list

University Academy | 37

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

numbers = [1, 3, 5, 7, 8, 9, 11, 12, 13]


for num in numbers:
if num % 2 == 0:
print("The first even number is:", num)
break

● Continue statement:
The continue statement is used to skip the current iteration of a loop and move on to the
next iteration. When a continue statement is encountered inside a loop, the current
iteration is terminated immediately, and the control is transferred to the next iteration of

y
the loop. This is useful when you want to skip over certain elements in a loop.
Here is an example of using the continue statement:

em
# Print all odd numbers in a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
continue
print(num) ad
Ac
3. Attempt any two of the following: 4*2 = 8
a. What do you mean by operator precedence and associativity. Explain
ity

Operator Precedence:

Operator precedence refers to the order in which operators are evaluated in an expression.
In Python, some operators have higher precedence than others, which means that they are
es

evaluated before other operators in the expression.


iv

For example, in the expression 2 + 3 * 4, the multiplication operation 3 * 4 is evaluated first


because it has higher precedence than the addition operation 2 + 12. Therefore, the result
of the expression is 14.
Un

Operator precedence in Python (from highest to lowest):


1. Parentheses ()
2. Exponentiation **
3. Unary operators -, +
4. Multiplication *, Division /, Floor division //, Modulus %
5. Addition +, Subtraction -
6. Comparison operators <, >, <=, >=, ==, !=
7. Logical operators not, and, or

University Academy | 38

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Operator Associativity:
Operator associativity refers to the direction in which operators are evaluated when they
have the same precedence in an expression. In Python, some operators are left-associative,
which means that they are evaluated from left to right, while others are right-associative,
which means that they are evaluated from right to left.

For example, the exponentiation operator ** is right-associative, which means that in the
expression 2 ** 3 ** 2, the exponentiation operation 3 ** 2 is evaluated first, resulting in 9,
and then the exponentiation operation 2 ** 9 is evaluated, resulting in the final value of
512.

y
Operator associativity in Python:

em
1. Exponentiation ** (right-associative)
2. Unary operators -, + (right-associative)

4. Addition +, Subtraction - (left-associative)


ad
3. Multiplication *, Division /, Floor division //, Modulus % (left-associative)

5. Comparison operators <, >, <=, >=, ==, != (left-associative)


Ac
6. Logical operators not (right-associative), and (left-associative), or (left-associative)
7.
b. Write short notes on
i. The programming cycle for python
ity

Refer Page: 03
ii. Type conversion in python
Python Type conversion with the help of examples. In programming, type conversion is the
es

process of converting data of one type to another. For example: converting int data to str.
There are two types of type conversion in Python.
iv

● Implicit Conversion - automatic type conversion


● Explicit Conversion - manual type conversion
Un

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known
as implicit type conversion.
Example 1: Converting integer to float
Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number
# display new value and resulting data type

University Academy | 39

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

print("Value:",new_number)
print("Data Type:",type(new_number))
Output
Value: 124.23
Data Type: <class 'float'>

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type
conversion. This type of conversion is also called typecasting because the user casts

y
(changes) the data type of the objects.
Python provides several built-in functions that allow you to convert between different data

em
types:

○ int(): Converts a value to an integer data type. For example, int(3.5) will return 3.


return 3.0.
ad
float(): Converts a value to a floating-point data type. For example, float(3) will

str(): Converts a value to a string data type. For example, str(3.5) will return the
Ac
string '3.5'.
○ bool(): Converts a value to a Boolean data type. For example, bool(0) will return
False.
○ list(): Converts a value to a list data type. For example, list("hello") will return the
ity

list ['h', 'e', 'l', 'l', 'o'].


○ tuple(): Converts a value to a tuple data type. For example, tuple([1, 2, 3]) will
return the tuple (1, 2, 3).
es

○ set(): Converts a value to a set data type. For example, set([1, 2, 3, 3]) will return
the set {1, 2, 3}.
○ dict(): Converts a value to a dictionary data type. For example, dict([('a', 1), ('b',
iv

2)]) will return the dictionary {'a': 1, 'b': 2}.


Un

c. Write Python program to swap two numbers without using Intermediate /


Temporary variables. Prompt the user for input.
# Prompt the user for input
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Before swapping
print("Before swapping: num1 =", num1, "and num2 =", num2)
# Swap the numbers
num1 = num1 + num2

University Academy | 40

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

num2 = num1 - num2


num1 = num1 - num2
# After swapping
print("After swapping: num1 =", num1, "and num2 =", num2)
Output:
Enter the first number: 13
Enter the second number: 43
Before swapping: num1 =13, and num2 = 43
After swapping: num1 =43, and num2 = 13

y
4. Attempt any two of the following: 4*2 = 8

em
a. Write a program to check an input number is prime or not.

num = int(input("Enter a number: "))

if num > 1:
for i in range(2, num):
if (num % i) == 0: ad
Ac
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
ity

else:
print(num, "is not a prime number")
es

Sample output:
Enter a number: 13
13 is a prime number
iv

b. Write a program that accepts a sentence and calculate the number of digits,
Un

uppercase and lowercase letters.

sentence = input("Enter a sentence: ")


digit_count = 0
upper_count = 0
lower_count = 0
for char in sentence:
if char.isdigit():
digit_count += 1
elif char.isupper():
upper_count += 1

University Academy | 41

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

elif char.islower():
lower_count += 1

print("Number of digits:", digit_count)


print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)
Sample output:
Enter a sentence: The quick Brown Fox Jumps over 2 lazy DOGS
Number of digits: 1
Number of uppercase letters: 8

y
Number of lowercase letters: 25
c. Write a program to check an input year is leap year or not.

em
year = int(input("Enter a year: "))

if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):


print(year, "is a leap year")
else:
print(year, "is not a leap year")
ad
Ac
Sample output:

Enter a year: 2020


2020 is a leap year
ity

Enter a year: 2021


2021 is not a leap year
es

5. Attempt any two of the following: 4*2 = 8


a. There is a file named Input.Txt. Enter some positive numbers into the file
iv

named Input.Txt. Read the contents of the file and if it is an odd number
write it to ODD.TXT and if the number is even, write it to EVEN.TXT
Un

with open("Input.txt", "r") as input_file, open("EVEN.txt", "w") as


even_file, open("ODD.txt", "w") as odd_file:
for line in input_file:
number = int(line.strip())
if number % 2 == 0:
even_file.write(str(number) + "\n")
else:
odd_file.write(str(number) + "\n")

Assuming that the file Input.txt contains the following numbers:


5
6
8

University Academy | 42

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

3
9
10
The program will create two new files EVEN.txt and ODD.txt in the same directory as the
program file.

The EVEN.txt file will contain the even numbers:


6
8
10

And the ODD.txt file will contain the odd numbers:

y
5
3

em
9

b. Discuss Exceptions and Assertions in Python. Explain with a suitabl


example. Explain any two built-in exceptions.
● Exceptions in Python

ad
When a program encounters an error, it raises an exception object that can be caught and
handled by the program. Python has many built-in exceptions, such as ZeroDivisionError,
TypeError, and ValueError. In addition to the built-in exceptions, we can also create our own
Ac
exceptions by creating a new class that inherits from the Exception class.
Here's an example that shows how to handle the ZeroDivisionError exception:
try:
ity

x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
es

In this example, we try to divide the number 1 by 0, which raises a ZeroDivisionError. We


catch the exception using a try/except block and print an error message.
iv

● Assertions in Python
Assertions are used to check the correctness of a program's assumptions. An assertion is a
Un

statement that should be true at a certain point in the program's execution. If the assertion
is false, Python raises an AssertionError. We use assertions to catch errors early during
development and testing.
Here's an example that uses assertions to check the input to a function:
def average(numbers):
assert len(numbers) > 0, "List is empty"
return sum(numbers) / len(numbers)
In this example, we define a function average that calculates the average of a list of
numbers. We use an assertion to check that the input list is not empty. If the input list is
empty, an AssertionError is raised with the specified error message.

University Academy | 43

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Built-in Exceptions in Python


Python has many built-in exceptions that can be raised in different situations. Here are two
examples of built-in exceptions:
● TypeError: This exception is raised when an operation or function is applied to an
object of inappropriate type.
x = 5
y = "hello"
z = x + y # Raises a TypeError
In this example, we try to add a number (x) and a string (y), which raises a TypeError.

y
● IndexError: This exception is raised when an attempt is made to access an index

em
that is out of range.
my_list = [1, 2, 3]
print(my_list[3]) # Raises an IndexError

ad
In this example, we try to access the fourth element of the list my_list, which raises an
IndexError.
Ac
c. What is the significance of module in Python? What are the methods of importing a
module? Explain with suitable example
A module in Python is a file that contains a set of functions, classes, and variables that can
be used in other Python programs. Modules are used to organize code into logical units and
ity

to avoid naming conflicts. By using modules, we can reuse code, save time, and make our
programs more efficient.
es

Python has a lot of built-in modules that come with the standard library, such as math,
datetime, os, and random. We can also create our own modules by creating a new file with
a .py extension and defining functions, classes, or variables in it.
iv
Un

There are three methods of importing a module in Python:


● import module_name: This method imports the entire module and makes all its
functions, classes, and variables available in the program.
import math
result = math.sqrt(16)
print(result) # Output: 4.0

In this example, we import the math module and use its sqrt() function to calculate the
square root of 16.

University Academy | 44

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

● from module_name import function_name: This method imports a specific


function from the module and makes it available in the program.

from math import sqrt


result = sqrt(16)
print(result) # Output: 4.0

In this example, we import the sqrt() function from the math module and use it to calculate
the square root of 16.
● import module_name as alias_name: This method imports the entire module and

y
gives it an alias that can be used in the program.
import math as m

em
result = m.sqrt(16)
print(result) # Output: 4.0

ad
In this example, we import the math module and give it an alias m. We use the alias m to
call the sqrt() function and calculate the square root of 16.
Ac
6. Attempt any two of the following: 4*2 = 8
a. What do you mean by recursion? Write a recursive function to compute the factorial of
an input number N.
ity

Recursion is a programming technique in which a function calls itself repeatedly until it


reaches a base case, where the function returns a value without making any further
recursive calls. Recursion is a powerful tool for solving problems that can be broken down
es

into smaller, similar subproblems.

Here is an example of a recursive function in Python that computes the factorial of an input
iv

number N:
def factorial(n):
Un

if n == 0:
return 1
else:
return n * factorial(n-1)
n = int(input("Enter a number to compute the factorial of: "))
result = factorial(n)
print(f"The factorial of {n} is {result}")

Sample Output:
Enter a number to compute the factorial of: 5

University Academy | 45

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

The factorial of 5 is 120

Working:
factorial(5) = 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1 * factorial(0)
= 5 * 4 * 3 * 2 * 1 * 1
= 120

y
b. Implement selection sort using Python
Refer Page: 17

em
c. What are different types of inheritance supported by Python? Explain
Python supports several types of inheritance, including:
1. Single Inheritance: Single inheritance enables a derived class to inherit properties

ad
from a single parent class, thus enabling code reusability and the addition of new
features to existing code.
Ac
2. Multiple inheritance: In multiple inheritance, a subclass inherits from multiple
parent classes. This allows a class to inherit functionality from multiple sources, but
can be complex to implement and can lead to naming conflicts.
ity

3. Multi-level inheritance: In multi-level inheritance, a subclass inherits from a parent


class, which in turn inherits from its own parent class, and so on. This forms a
hierarchy of classes, with each level of the hierarchy inheriting from the level
es

above it.
iv

4. Hierarchical inheritance: In hierarchical inheritance, multiple subclasses inherit


from a single parent class. This allows for multiple subclasses to share functionality
Un

and attributes from a common parent class.

5. Hybrid inheritance: Hybrid inheritance is a combination of any of the above types of


inheritance.

University Academy | 46

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

y
Hybrid inheritance

em
Here's an example of single inheritance in Python:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
ad
Ac
pass
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
ity

def make_sound(self):
return "Woof!"
my_dog = Dog("Rover")
es

print(my_dog.make_sound()) # Output: "Woof!"


iv
Un

University Academy | 47

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

(SEM III) THEORY EXAMINATION 2020-21

SECTION A

1. Attempt all questions in brief.


a. What is the use of “raise” statement? Describe with an example
In Python, the raise statement is used to generate an exception manually. By raising an
exception, you can signal to the program that something unexpected has happened, and the
program should stop executing its current code path and start looking for an exception handler.

y
The basic syntax for raising an exception using raise statement is:

em
raise exception_type("Error message")
Here, exception_type is the type of exception that you want to raise, and "Error message" is the
message that will be displayed when the exception is raised.

ad
For example, you can use the raise statement to raise a ValueError exception when a function
receives an invalid argument:
Ac
def divide_numbers(a, b):
if b == 0:
raise ValueError("b cannot be zero")
return a / b
ity

if the b argument is zero, a ValueError exception will be raised with the message "b cannot be
zero"
b. Write a recursive Python function “rprint” to print all elements in a list in
es

reverse.
rprint([]) prints nothing
iv

rprint([1,2,3]) prints 3 2 1

def rprint(lst):
Un

if len(lst) == 0:
return
else:
print(lst[-1], end=' ')
rprint(lst[:-1])
Here are some sample outputs for the function:
rprint([])
# prints nothing

rprint([1, 2, 3])

University Academy | 48

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

# prints: 3 2 1
rprint([5, 6, 7, 8])
# prints: 8 7 6 5

c. Describe the behavior of “range (s, e)” in Python.


The range(s, e) function generates a sequence of numbers that starts from s and goes up to, but
does not include, e.

The range() function is a built-in function in Python that is used to generate a sequence of
numbers. It is often used in loops to repeat a block of code a specific number of times.

y
The basic syntax of the range() function is as follows:

em
range(start, stop, step)
● start: The starting value of the sequence (optional, defaults to 0).
● stop: The ending value of the sequence (required).
● step: The step value between each number in the sequence (optional, defaults to 1).

ad
When only two arguments are provided, as in range(s, e), the function generates a sequence of
numbers starting from s and going up to, but not including, e.
Ac
d. Explain the use of “with” construct in Python with an example program.
The with statement in Python is used to wrap the execution of a block of code with methods
defined by a context manager. The main advantage of using with is that it ensures that the
resources are properly managed and released after the execution of the block of code.
ity

The basic syntax of the with statement is as follows:


es

with context_manager as var:


program that uses the with statement to open and read a file:
iv

with open('example.txt', 'r') as f:


content = f.read()
Un

print(content)
assume that the file example.txt contains the following text:
This is an example file.
It contains some text that we will read using a Python program.

Then the output of the program would be:

This is an example file.


It contains some text that we will read using a Python program.

University Academy | 49

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

e. Which of the following statements produce an error in Python?


x, y, z = 1,2,3 # s1
a,b= 4,5,6 # s2
u= 7,8,9 # s3
S1: The statement x, y, z = 1, 2, 3 is valid in Python. Values 1, 2, and 3 to the variables x, y, and
z, respectively.
S2: The statement a,b=4,5,6 produces a ValueError in Python because the left-hand side of the
assignment has two variables (a and b), but the right-hand side has three values (4, 5, and 6).
S:3 The statement u = 7, 8, 9 is valid in Python and does not produce any errors. statement
assigns the tuple (7, 8, 9) to the variable u

y
f. Explain the role of precedence with an example.

em
Refer Page: 38

g. How do you read an input from a user in Python to be used as an integer in the rest of the
program? Explain with an example

ad
There are two ways to provide input information to a program. One in which we directly assign
input objects to object references/variables; and the other in which the program takes user
Ac
input dynamically (during runtime).
you can use the input() function to read a string input from the user, and then convert it to an
integer using the int() function. Here's an example:
ity

integer = int(input("Enter an integer as input: "))


print(integer*10)
print(type(integer))
es

Output
Enter an integer as input: 12
120
iv

<class 'int'>
Un

h. Consider the program:


x=['12', 'hello', 456]
x[0]*= 3
x[1][1]='bye'
Explain why this program generates an error.

X[0] *= 3 This statement tries to multiply thestring '12 ' by 3, which results in a new string
'121212 '. However, the original list X contains strings and an integer. Multiplying a string by an
integer is a valid operation in Python, but it creates a new string and replaces the original value

University Academy | 50

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

in the list. In this case, the new string '121212 ' is not compatible with the original integer and
string in the list.

X[1][1] = 'bye' - This statement tries to modify the second character of the string 'hello' to
'b'.However, strings in Python are immutable, which means that you cannot modify them
directly.Instead, you need to create a new string with the modified characters. In this case, the
attempt to modify the string 'hello' in-place generates an error.

i. What is the output of the following program?


(lambda x,y : y - 2*x) (1, 11)

y
The output of this Python program will be: 9

em
This program defines a lambda function with two arguments x and y, and returns the value y -
2*x. The lambda function is then immediately called with the arguments (1, 11).
Substituting x = 1 and y = 11 into the function gives:
11 - 2*1 = 9
j. Explain the use of lt function in a class Python?
ad
The __lt__ function is a special method that defines the behavior of the less than operator < for
Ac
objects of a class. It is used to implement the comparison of objects in a specific way.
Syntax: __lt__(self, obj)

● self: Reference of the object.


ity

● obj: It is an object that will be compared further with the other object.

Returns: Returns True or False depending on the comparison.


es

class Person:
def __init__(self, name, age):
iv

self.name = name
self.age = age
Un

def __lt__(self, other):


return self.age < other.age

University Academy | 51

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

SECTION B

2. Attempt any three of the following:


i. Write a Python function removekth(s, k) that takes as input a string s and an integer
k>=0 and removes the character at index k. If k is beyond the length of s, the whole of s
is returned. For example,
removekth(“PYTHON”, 1) returns “PTHON”
removekth(“PYTHON”, 3) returns “PYTON”
removekth(“PYTHON”, 0) returns “YTHON”
removekth(“PYTHON”, 20) returns “PYTHON”

y
Program :

em
def removekth(s, k):
if k >= len(s):

else:
return s

return s[:k] + s[k+1:]


ad
Ac
# Examples
print(removekth("PYTHON", 1)) # Output: "PTHON"
ity

print(removekth("PYTHON", 3)) # Output: "PYTON"


print(removekth("PYTHON", 0)) # Output: "YTHON"
print(removekth("PYTHON", 20)) # Output: "PYTHON"
es

ii. Write a Python function average to compute the average of a list of numbers. The
function must use try-except to handle the case where the input list is empty. Further,
in that case the average for the empty list should be set to 0.0 using the except block.
iv

Python function that calculates the average of a list of numbers while also handling the
Un

case where the input list is empty using try-except:


def average(numbers):
try:
result = sum(numbers) / len(numbers)
except ZeroDivisionError:
result = 0.0
return result
We use the try block to calculate the sum of the list of numbers and divide it by the length
of the list to get the average. If the length of the list is 0 and we try to divide by 0, then a

University Academy | 52

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

ZeroDivisionError will be raised. To handle this error, we use the except block to set the
average to 0.0

Sample output
>>> average([1, 2, 3, 4, 5])
3.0
>>> average([10, 20, 30])
20.0
>>> average([])

y
0.0
iii. Describe the differences between a linear search and a binary search?

em
Linear search and binary search are two algorithms used to search for an element in a list
of values. The main differences between them are:
● Algorithmic complexity: Binary search has a time complexity of O(log n) which

ad
means that it can search a sorted list of n elements in logarithmic time. On the
other hand, linear search has a time complexity of O(n) which means that it has to
traverse each element in the list one by one, making it less efficient for large lists.
Ac
● List requirements: Binary search requires the list to be sorted in ascending or
descending order, whereas linear search can be applied to any type of list, whether
ity

sorted or not.

● Search method: In a linear search, the algorithm starts at the beginning of the list
es

and checks each element sequentially until it finds the target value or reaches the
end of the list. In contrast, binary search divides the list into two halves and checks
iv

whether the target value is in the left or right half. This process is repeated
recursively on the relevant half until the target value is found.
Un

● Memory requirements: Binary search requires more memory than linear search as it
needs to keep track of the indices of the beginning and ending positions of the
sub-list being searched. Linear search, on the other hand, requires minimal memory
as it only needs to remember the current index being searched.

● Suitability for different scenarios: Binary search is more suitable for large sorted
lists where the target value is likely to be found closer to the middle of the list, as
it is a more efficient algorithm. Linear search is more suitable for small lists or

University Academy | 53

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

unsorted lists, where the cost of sorting the list or implementing binary search
outweighs the efficiency gains.

iv. Write a function lessthan(lst, k) to return list of numbers less than k from a list lst. The
function must use list comprehension. Example:
lessthan([1, -2, 0, 5, -3], 0) returns [-2, -3]

Program:
def lessthan(lst, k):

y
return [x for x in lst if x < k]

em
In this function, we create a new list using list comprehension that contains only those elements
from lst that are less than k. The if x < k condition in the comprehension ensures that only
those elements that satisfy this condition are included in the new list.

example of how to use the lessthan function:


lst = [1, -2, 0, 5, -3]
ad
Ac
k = 0
result = lessthan(lst, k)
print(result) # Output: [-2, -3]
we call the lessthan function with the list [1, -2, 0, 5, -3] and the integer 0. The function
ity

returns a new list [-2, -3] which contains only the elements of the original list that are less than
0.
v. Write a program factors(N) that returns a list of all positive divisors of N (N>=1). For
es

example:
factors(6) returns [1,2,3,6]
iv

factors(1) returns [1]


factors(13) returns [1,13]
Program:
Un

def factors(N):
divisors = []
for i in range(1, N+1):
if N % i == 0:
divisors.append(i)
return divisors
we create an empty list divisors to store the positive divisors of N. We then loop through all the
integers from 1 to N using the range function. For each integer i, we check whether it is a
divisor of N using the condition if N % i == 0. If i is a divisor of N, we append it to the divisors

University Academy | 54

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

list using the append method. Finally, we return the divisors list containing all the positive
divisors of N.
Example :
print(factors(6)) # Output: [1, 2, 3, 6]
print(factors(1)) # Output: [1]
print(factors(13)) # Output: [1, 13]

SECTION C

3. Attempt any one part of the following:

y
a. How can you create Python file that can be imported as a library as well as run as a

em
standalone script?
Python file that can be imported as a library as well as run as a standalone script, you can use
the if __name__ == '__main__' conditional statement in your Python file. This conditional
statement allows you to separate the code that is executed when the file is run as a standalone

ad
script from the code that is imported when the file is used as a library.

Here's an example of how you can create a Python file that can be imported as a library as well
Ac
as run as a standalone script:

# my_module.py
def my_function():
ity

print("Hello, world!")
if __name__ == '__main__':
my_function()
es

run this file as a standalone script, you can use the following command:
iv

python my_module.py
Un

This will execute the my_function function and print "Hello, world!" to the console.
import this file as a library, you can use the following code in another Python file:
# another_file.py
from my_module import my_function
my_function()
This will import the my_function function from the my_module module and execute it, printing
"Hello, world!" to the console.

b. Describe the difference between import library and from library import *
when used in a python program. Here library is some python library.

University Academy | 55

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

In Python, import library and from library import * are both used to import modules from a
Python library, but they work in slightly different ways.

When you use import library, it imports the whole module library into your program's
namespace. This means that to use any function or object from library, you need to prefix it
with the module name. For example, if you import the math module using import math, you
would need to call the sqrt function like this:

import math

y
x = math.sqrt(4)

em
when you use from library import *, it imports all of the functions and objects from the
library module directly into your program's namespace. This means that you can use them
without the module prefix. For example, if you import the math module using from math
import *, you can call the sqrt function directly:

from math import *


ad
Ac
x = sqrt(4)
generally not recommended to use from library import * because it can cause naming conflicts
and make it harder to understand where functions and objects are coming from.
ity

4. Attempt any one part of the following:


a. Write a function makePairs that takes as input two lists of equal length and returns a single
list of same length where k-th element is the pair of k-th elements from the input lists. For
es

example,
makePairs([1,3,5,7],[2,4,6,8])
iv

returns [(1,2),(3,4),(5,6),(7,8)]
makePairs([],[])
Un

returns []

function in Python:
def makePairs(list1, list2):
"""Returns a list of tuples containing pairs of elements from list1 and
list2."""
pairs = []
for i in range(len(list1)):
pairs.append((list1[i], list2[i]))
return pairs

Here are some examples of using the makePairs function:

University Academy | 56

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

>>> makePairs([1,3,5,7],[2,4,6,8])
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>> makePairs([],[])
[]
>>> makePairs([1,2,3], [4,5,6])
[(1, 4), (2, 5), (3, 6)]

b. Show an example where both Keyword arguments and Default arguments are used for the
same function in a call. Show both the definition of the function and its call
def greet(name, greeting='Hello'):

y
print(greeting + ', ' + name + '!')

em
greet(name='Alice', greeting='Hi')

The greet function takes in two arguments - name and greeting. The greeting argument has a
default value of 'Hello'.

ad
When the function is called, the name argument is passed as a keyword argument with the
Ac
value 'Alice', while the greeting argument is also passed as a keyword argument with the value
'Hi'. Since the greeting argument is explicitly passed, it overrides the default value of 'Hello'.
The output of the above code would be:
ity

Hi, Alice!

b. Attempt any one part of the following:


es

i. Explain why Python is considered an interpreted language


Refer Page: 27
ii. What is short circuit evaluation? What is printed by the following Python
iv

program?
a = 0
Un

b = 2
c = 3
x = c or a
print(x)
Short circuit evaluation is a boolean evaluation strategy in which the second operand of a logical
expression is only evaluated if necessary. In other words, if the first operand is sufficient to
determine the result of the expression, then the second operand is not evaluated.
output of the program will be: 3

University Academy | 57

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

5. Attempt any one part of the following:


a. Write a Python program, triangle(N), that prints a right triangle having base and height
consisting of N * symbols as shown in these examples:
triangle(3) prints:
*
**
***

triangle(5) prints:
*

y
**
***

em
****
*****

ad
Python program that uses a loop to print a right triangle with base and height consisting of N
asterisks:
Ac
def triangle(N):
for i in range(1, N+1):
print('*' * i)
ity

print a triangle with base and height of 5 asterisks:

triangle(5)
es

*
**
***
iv

****
*****
Un

b. Write a Python program, countSquares(N), that returns the count of perfect squares less than
or equal to N (N>1). For example:

countSquares(1) returns 1
# Only 1 is a perfect square <= 1
countSquares(5) returns 2
# 1, 4 are perfect squares <= 5
countSquares(55) returns 7
# 1, 4, 9, 16, 25, 36, 49 <= 55

University Academy | 58

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

Python program that uses a loop to count the number of perfect squares less than or equal to N:

def countSquares(N):
count = 0
i = 1
while i * i <= N:
count += 1
i += 1
return count

y
some sample outputs of the countSquares(N)
print(countSquares(55))

em
7
countSquares(5) => 2
countSquares(10) => 3
countSquares(15) => 3
countSquares(20) => 4
countSquares(25) => 5
countSquares(30) => 5
ad
Ac
countSquares(35) => 5
countSquares(40) => 6
countSquares(45) => 6
ity

countSquares(50) => 7

6. Attempt any one part of the following:


es

a. Write a Python function, alternating(lst), that takes as argument a sequence lst. The function
returns True if the elements in lst are alternately odd and even, starting with an even
number. Otherwise it returns False. For example:
iv

alternating([10, 9, 9, 6]) returns False


alternating([10, 15, 8]) returns True
Un

alternating([10]) returns True


alternating([]) returns True
alternating([15, 10, 9]) returns False

Python function that checks if a list alternates odd and even numbers, starting with an even
number:

def alternating(lst):
if len(lst) == 0:
return True

University Academy | 59

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

elif len(lst) == 1:
return lst[0] % 2 == 0
else:
if lst[0] % 2 != 0:
return False
for i in range(1, len(lst)):
if lst[i] % 2 == lst[i-1] % 2:
return False
return True

y
sample outputs of the alternating(lst) function:
alternating([10, 9, 9, 6]) => False

em
alternating([10, 15, 8]) => True
alternating([10]) => True
alternating([]) => True
alternating([15, 10, 9]) => False

ad
b. Write a Python function, searchMany(s, x, k), that takes as argument a sequence s and
integers x, k (k>0). The function returns True if there are at most k occurrences of x in s.
Ac
Otherwise it returns False. For example:
searchMany([10, 17, 15, 12], 15, 1) returns True
searchMany([10, 12, 12, 12], 12, 2) returns False
ity

searchMany([10, 12, 15, 11], 17, 18) returns True


Python function that checks if a sequence s contains at most k occurrences of the integer x:
es

def searchMany(s, x, k):


count = 0
for item in s:
iv

if item == x:
count += 1
Un

if count > k:
return False
return True

Sample outputs of the searchMany(s, x, k) function:


searchMany([10, 17, 15, 12], 15, 1) => True
searchMany([10, 12, 12, 12], 12, 2) => False
searchMany([10, 12, 15, 11], 17, 18) => True

University Academy | 60

Downloaded by Anisha Kushwaha ([email protected])


lOMoARcPSD|56238245

y
em
ad
Ac
ity
es
iv
Un

University Academy | 61

Downloaded by Anisha Kushwaha ([email protected])

You might also like