Python Paper Solution
Python Paper Solution
y
Dr. A. P. J. Abdul Kalam Technical
em
University, Lucknow
PYTHON PROGRAMMING
ad
Ac
Previous Year Solved Paper
ity
es
iv
Un
University Academy | 1
Index
y
em
ad
Ac
ity
es
iv
Un
University Academy | 2
y
4. Debug the code
em
5. Repeat 2-4 until the program runs correctly.
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
University Academy | 3
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.
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
● 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'}
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
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
1. len(): This function returns the length of a string, which is the number of characters in the
es
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
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']
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
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
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.
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
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
output
Enter a number: 12345
The reverse of the entered number is: 54321
iv
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
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
print(my_list)
Output
[1, 2, 3, 4, 5]
iv
[1, 3, 4, 5]
3. List Comprehension:
Un
University Academy | 10
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
(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
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}")
University Academy | 12
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.
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
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
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()
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
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
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')
(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
University Academy | 15
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)
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
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
(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
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
(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
University Academy | 18
# 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
SECTION A
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
x = cube(3)
print x
The given code will produce the following output:
iv
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
i. Linear search
ii. Binary search
iii. Depth-first search (DFS)
iv. Breadth-first search (BFS)
SECTION B
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.
University Academy | 21
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.
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.
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
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
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:
University Academy | 23
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
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
University Academy | 24
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.
if n == 1:
print(f"Move disk {n} from {source} to {target}")
else:
es
# Example usage
Un
University Academy | 25
SECTION C
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.
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
return arr
University Academy | 26
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
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
University Academy | 28
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
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
52341
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
University Academy | 30
# Defining a function
def UA():
print("UniversityAcademy")
# Defining a variable
location = "Noida"
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
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.
def sieve_of_eratosthenes(n):
primes = [True] * (n+1)
primes[0] = primes[1] = False
University Academy | 31
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.
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
r: The upper bound of the sublist to search (initially set to the length of the list
minus one)
Un
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
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
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.
University Academy | 33
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
SECTION A
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
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.
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
● 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 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
SECTION B
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 = []
avg = ComputeAverage(numbers)
print(avg) # Output: 0
iv
● 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
● 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
University Academy | 38
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)
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
University Academy | 39
print("Value:",new_number)
print("Data Type:",type(new_number))
Output
Value: 124.23
Data Type: <class 'float'>
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
○ 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
University Academy | 40
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.
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
University Academy | 41
elif char.islower():
lower_count += 1
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: "))
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
University Academy | 42
3
9
10
The program will create two new files EVEN.txt and ODD.txt in the same directory as the
program file.
y
5
3
em
9
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
● 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
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
In this example, we import the math module and use its sqrt() function to calculate the
square root of 16.
University Academy | 44
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
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
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
above it.
iv
University Academy | 46
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
University Academy | 47
SECTION A
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
# prints: 3 2 1
rprint([5, 6, 7, 8])
# prints: 8 7 6 5
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
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.
University Academy | 49
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
Output
Enter an integer as input: 12
120
iv
<class 'int'>
Un
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
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.
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)
● obj: It is an object that will be compared further with the other object.
class Person:
def __init__(self, name, age):
iv
self.name = name
self.age = age
Un
University Academy | 51
SECTION B
y
Program :
em
def removekth(s, k):
if k >= len(s):
else:
return s
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
University Academy | 52
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
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.
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
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
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
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
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:
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
University Academy | 56
>>> 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!
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
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
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
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
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
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
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
if item == x:
count += 1
Un
if count > k:
return False
return True
University Academy | 60
y
em
ad
Ac
ity
es
iv
Un
University Academy | 61