(Sem Iii) (Aktu) Python Theory Examination 2022-23 Solution
(Sem Iii) (Aktu) Python Theory Examination 2022-23 Solution
PYTHON PROGRAMMING
Demonstrate five different built in functions used in the string. Write a program to check whether a string
is a palindrome or not.
def is_palindrome(s):
# Remove spaces and convert to lowercase for uniformity
s = s.replace(" ", "").lower()
# Reverse the string and check if it is the same as the original
return s == s[::-1]
# User input
string = input("Enter a string: ")
# Check for palindrome
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
@rishabh.real
Explain the following loops with a flow diagram, syntax, and suitable
examples.I) For II) while
Syntax
Example
Syntax
while condition:
# Code to execute
Example
i = 0
while(i < 10):
print(i)
i+=1
@rishabh.real
Explain the continue, break, and pass statements with a suitable example.
In Python, continue, break, and pass are control flow statements used to manage loop execution.
continue statement skips the current iteration and moves to the next iteration of the loop.
for num in range(1, 6):
if num == 3:
continue # Skip the rest of the loop for num == 3
print(num)
def reverse_number(n):
rev = 0
while n > 0:
digit = n % 10 # Extract last digit
rev = rev * 10 + digit # Append digit to reverse number
n = n // 10 # Remove last digit from original number
return rev
# Get user input
num = int(input("Enter a positive number: "))
# Calculate and display reverse
if num >= 0:
print("Reversed number:", reverse_number(num))
else:
print("Please enter a positive number!")
@rishabh.real
Explain the list Comprehension with any suitable example.
List comprehension is a concise way to create lists using a single line of code. It is more readable and faster
than using loops.
Example
@rishabh.real
Illustrate Unpacking Sequences, Mutable Sequences, and List comprehension with examples.
Unpacking is the process of extracting elements from a sequence (like lists, tuples, or strings) and
assigning them to variables. In Python, unpacking can be done in a very concise manner, which
makes it a powerful tool for handling sequences.
The * operator allows for a flexible unpacking mechanism. You can use it to capture a
variable-length part of the sequence, which is useful when you're not sure about the exact number of
elements.
Mutable sequences allow us to change their contents without creating new objects. This includes
adding, removing, or changing elements.
@rishabh.real
Explain the lambda function. How it is helpful in the higher order function. Explain map() function with a
suitable example.
A lambda function in Python is a small anonymous function, defined using the lambda keyword. It can
have any number of input parameters, but it can only contain a single expression. The result of this
expression is automatically returned without needing to use a return statement.
For example, using lambda with the map(), filter(), and sorted() functions (all of which are
higher-order functions) allows you to apply simple operations without defining a full function.
Syntax:
map(function, iterable)
Example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
@rishabh.real
Discuss the different types of argument-passing methods in python. Explain
the variable length argument with any suitable example.
In Python, function arguments can be passed in several ways, allowing flexibility and clarity in how functions
are called and how data is handled. The main types of argument-passing methods in Python are:
@rishabh.real
2. Arbitrary Keyword Arguments (using **kwargs)
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, country="USA")
Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data
within a class and restricting direct access to some of the object's components. This is done using access
modifiers like private (__) or protected (_).
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). It
enables code reuse and the creation of hierarchical relationships between classes.
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
@rishabh.real
labrador = Dog()
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
# call subclass method
labrador.display()
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.
File handling in Python allows you to create, read, write, and manipulate files on your system. Python
provides built-in functions for file operations, such as open(), read(), write(), and close().
There are various modes to open file but these are few basic modes to open a file:
1. Write Mode ('w'): This mode is used to write to a file. If the file does not exist, it will be created. If the
file exists, its contents will be overwritten.
2. Read Mode ('r'): This mode is used to read the content of the file. The file must exist to be read.
3. Append Mode ('a'): This mode is used to add content to an existing file without overwriting the
existing data.
@rishabh.real
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 ancient algorithm used to find all prime numbers up to a given limit. It works
by iteratively marking the multiples of each prime number starting from 2. The numbers that remain
unmarked are prime numbers.
def sieve_of_eratosthenes(limit):
# Step 1: Create a boolean list of size 'limit+1' to mark prime numbers
primes = [True] * (limit + 1)
primes[0] = primes[1] = False # 0 and 1 are not prime numbers
# Step 2: Mark all multiples of prime numbers as False (not prime)
for i in range(2, int(limit ** 0.5) + 1):
if primes[i]: # If i is prime
for j in range(i * i, limit + 1, i): # Mark all multiples of i as not
prime
primes[j] = False
# Step 3: Print all prime numbers
for i in range(2, limit + 1):
if primes[i]:
print(i, end=" ")
# Call the function to print prime numbers between 1 and 100
sieve_of_eratosthenes(100)
@rishabh.real
Develop and write the python code of selection sort to sort 41,65,43,91,12,14,62 elements. Also, explain its
complexity.
def selection_sort(arr):
# Loop through the entire array
for i in range(len(arr)):
# Find the minimum element in the remaining unsorted part of the array
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
# Swap the found minimum element with the first unsorted element
arr[i], arr[min_index] = arr[min_index], arr[i]
# List of elements to be sorted
arr = [41, 65, 43, 91, 12, 14, 62]
# Call the selection_sort function
selection_sort(arr)
# Print the sorted list
print("Sorted Array:", arr)
Time Complexity:
● Best Case: O(n^2) — Even if the list is already sorted, selection sort still compares every element to
find the minimum, leading to a quadratic time complexity.
● Worst Case: O(n^2) — This occurs when the list is in reverse order. Every element will need to be
compared with all others.
● Average Case:O(n^2) — For a random order of elements, the selection sort algorithm will still have
quadratic time complexity.
Space Complexity:
● Space Complexity: O(1) — Selection sort is an in-place sorting algorithm, meaning it requires only a
constant amount of additional space. It sorts the list without using extra memory.
@rishabh.real
Explain Binary search with its python code and complexity.
Binary search is an efficient algorithm used to search for a target value within a sorted array or list. It works
by repeatedly dividing the search interval in half. If the value of the target is less than the value in the middle
of the interval, the search continues in the lower half, otherwise in the upper half. This process is repeated
until the target value is found or the interval is empty.
Time Complexity:
● Best Case: O(1) — The target is found at the middle element in the first comparison.
● Worst Case: O(logn) — Each comparison reduces the search range by half, so after log n iterations,
the target will be found or the search range will be empty.
● Average Case: O(logn) — On average, binary search performs logarithmic comparisons.
Space Complexity:
● Space Complexity: O(1)O(1)O(1) — Binary search uses only a constant amount of extra space (the
pointers low, high, and mid), so it is an in-place algorithm.
@rishabh.real
Explain the importance of Exception handling in any object-oriented
programming language. Explain try exceptions and finally block with any suitable example.
Instead of allowing the program to crash, exception handling ensures that the program can handle errors
gracefully, providing a better user experience and more robust applications.
1. Graceful Error Handling: Instead of a program abruptly stopping when an error occurs, exceptions
allow the program to handle errors, log them, and proceed with other tasks.
2. Improved Readability and Maintainability: By separating normal code and error-handling code,
exception handling makes the program more readable and easier to maintain.
3. Avoiding Program Crashes: Without exception handling, any unexpected event (like division by
zero or accessing a file that doesn't exist) would cause the program to terminate. Exception handling
ensures that errors are dealt with without crashing the application.
4. Code Separation: Exception handling separates error-handling logic from the main program flow,
keeping the code clean and modular.
Syntax
try:
# Code that might raise an exception
except ExceptionType as e:
# Code that handles the exception
finally:
# Code that runs no matter what (optional)
Example
def divide_numbers(a, b):
try:
result = a / b
print("Result:", result)
except Exception as e:
print("An unexpected error occurred:", e)
finally:
print("Execution of the try-except block is complete.")
# Example usage
divide_numbers(10, 2) # Normal division
divide_numbers(10, 0) # Division by zero
@rishabh.real
Summarize the ‘Tower of Hanoi’ puzzle and write its recursive function to
implement it.
The Tower of Hanoi is a classic problem in computer science and mathematics. The puzzle consists of
three rods and a set of disks of different sizes that can slide onto any rod. The puzzle starts with all disks
stacked on one rod in ascending order of size, with the smallest disk on top.
Rules:
1. Move one disk at a time.
2. A disk can only be moved to the top of a rod if it is smaller than the disk already present on that rod.
3. The goal is to move all disks from the starting rod to the destination rod, using the auxiliary rod for
temporary storage.
SHORT ANSWERS
@rishabh.real
Explain the Programming Cycle for Python in detail.
1. Writing Code: You write the Python code using a text editor or Integrated Development Environment
(IDE). The code is typically saved with a .py extension.
2. Compilation: Python is an interpreted language, which means there is no separate compilation step
like in languages such as C or Java. When you run the Python code, the interpreter reads the code
line by line, converting it into bytecode.
3. Execution: The Python interpreter executes the bytecode on the fly, one statement at a time. This
means that Python code is executed dynamically, making it easy to test and debug.
4. Error Handling: If an error occurs (e.g., syntax error, runtime error), the interpreter raises an
exception and halts the execution, showing the error message.
5. Optimization: Although Python doesn't have a separate compilation phase, the interpreter may
optimize some parts of the code, such as reusing compiled bytecode for faster execution in
subsequent runs.
List Slicing in Python refers to extracting a portion (sub-list) of a list using the slicing syntax
list[start:end:step]
Example
my_list = [10, 20, 30, 40, 50, 60, 70]
# Slice from index 2 to 5 (exclusive)
sliced_list = my_list[2:5]
print(sliced_list) # Output: [30, 40, 50]
# Slice with a step of 2
sliced_list = my_list[1:6:2]
print(sliced_list) # Output: [20, 40, 60]
import math
print(math.sqrt(16)) # Output: 4.0
@rishabh.real
Array List
Stores elements of the same type (homogeneous) Stores elements of different types (heterogeneous)
Requires importing libraries like array or numpy Built-in data structure; no import needed
Fixed size once created Dynamic size; can grow or shrink as needed
Supports direct arithmetic operations Does not support direct arithmetic operations
Floor Division in Python uses the // operator to divide two numbers and return the largest integer that is
less than or equal to the result (i.e., rounding down).
x = 17
y = 5
result = x // y
print(result) # Output: 3
extend(): Adds all elements of an iterable (such as another list or tuple) to the end of the list.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
A Dictionary in Python is a collection of key-value pairs. Each key must be unique, and values can be of
any data type.
@rishabh.real
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes. It
focuses on encapsulating data and functionality within objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an object of the class
person1 = Person("Alice", 25)
person1.greet() # Output: Hello, my name is Alice and I am 25 years old.
Explanation: The function count1() counts the number of vowels (both uppercase and lowercase) in the
string 'I love India'.
Output: 6
M@o@n@k@y
@rishabh.real