[go: up one dir, main page]

0% found this document useful (0 votes)
35 views17 pages

(Sem Iii) (Aktu) Python Theory Examination 2022-23 Solution

The document provides an overview of various Python programming concepts, including built-in string functions, loops, control flow statements, file handling, and sorting algorithms. It includes examples of string manipulation, the Sieve of Eratosthenes for finding prime numbers, and selection sort for sorting a list of numbers. Additionally, it covers encapsulation and inheritance in object-oriented programming, as well as argument-passing methods in functions.

Uploaded by

rishabhyadav7923
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)
35 views17 pages

(Sem Iii) (Aktu) Python Theory Examination 2022-23 Solution

The document provides an overview of various Python programming concepts, including built-in string functions, loops, control flow statements, file handling, and sorting algorithms. It includes examples of string manipulation, the Sieve of Eratosthenes for finding prime numbers, and selection sort for sorting a list of numbers. Additionally, it covers encapsulation and inheritance in object-oriented programming, as well as argument-passing methods in functions.

Uploaded by

rishabhyadav7923
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/ 17

(SEM III) THEORY EXAMINATION 2022-23

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.

1. upper() – Converts a string to uppercase

text = "hello world"​


print("Uppercase:", text.upper()) # Output: "HELLO WORLD"

2. lower() – Converts a string to lowercase


text = "Hello World"​
print("Lowercase:", text.lower()) # Output: "hello world"

3. strip() – Removes leading and trailing spaces


text = " Python "​
print("Stripped:", text.strip()) # Output: "Python"

4. replace(old, new) – Replaces occurrences of a substring with another


text = "I love Java"​
print("Replaced:", text.replace("Java", "Python")) # Output: "I love Python"

5. find(substring) – Returns the index of the first occurrence of a substring


text = "Programming is fun"​
print("Position of 'is':", text.find("is")) # Output: 13

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

A for loop in Python is used to iterate over a sequence


(like a list, tuple, dictionary, or range).

Syntax

for variable in sequence:​


# Code to execute​

Example

for i in range(1, 6): # Loops from 1 to 5​


print(f"Iteration {i}")

The while loop is used to execute a set of statements as


long as a condition is true.

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)

break exits the loop completely when encountered.


for num in range(1, 6):​
if num == 3:​
break # Exit the loop when num == 3​
print(num)

pass acts as a placeholder; it does nothing and avoids syntax errors.


for num in range(1, 6):​
if num == 3:​
pass # Does nothing, just a placeholder​
print(num)

Develop a program to calculate the reverse of any entered number.

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.

new_list = [expression for item in iterable if condition]

Example

Using Loop Using List Comprehension

squares = []​ squares = [x ** 2 for x in range(1, 6)]​


for x in range(1, 6):​ print(squares)​
squares.append(x ** 2)​
print(squares)​

@rishabh.real
Illustrate Unpacking Sequences, Mutable Sequences, and List comprehension with examples.

1.​ Unpacking Sequence

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.

data = (10, 20, 30)​


a, b, c = data # Unpack the tuple into variables a, b, and c​
print(a, b, c)

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.

numbers = [1, 2, 3, 4, 5]​


first, second, *rest = numbers # Unpack first two elements and capture the
rest in 'rest'​
print(first, second, rest)

2.​ Mutable Sequence


In Python, sequences are categorized into mutable and immutable sequences. Mutable sequences
are those that can be changed after creation. Lists are the most common mutable sequence type in
Python,

Mutable sequences allow us to change their contents without creating new objects. This includes
adding, removing, or changing elements.

Example: Modifying a List (Mutable Sequence)

fruits = ["apple", "banana", "cherry"]​


fruits[1] = "blueberry" # Change the second element​
print(fruits)

3.​ List Comprehension


List comprehension provides a syntactically elegant way to create and manipulate lists in Python. It
allows you to generate a new list by applying an expression to each item in an iterable (such as a
list, range, or string).

squares = [x ** 2 for x in range(1, 6)]​


print(squares)

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

How Lambda Functions are Helpful in Higher-Order Functions


A higher-order function is a function that takes another function as an argument or returns a function as its
result. Lambda functions are often used in higher-order functions to create simple, one-time-use functions
that you don't want to name.

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.

The map() function


The map() function is a built-in Python function that allows you to apply a specified function to every item of
an iterable (like a list) and returns a map object (which is an iterator). The map() function is especially useful
when combined with a lambda function to apply an operation to all elements in a sequence.

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:

1.​ Positional Arguments


In this method, the arguments are passed to a function in the order in which they are defined in the
function definition. The number of arguments must match the number of parameters
def add(a, b):​
return a + b​

result = add(3, 5) # Positional argument: '3' is assigned to 'a', '5' to 'b'​
print(result) # Output: 8

2.​ Keyword Arguments​


Keyword arguments allow you to pass values to a function by explicitly specifying the parameter
name. This method is useful when you want to assign values to specific parameters without worrying
about their order.
def greet(name, message):​
print(f"Hello, {name}! {message}")​

greet(message="Welcome to Python!", name="Alice")

3.​ Default Arguments


A function can have default values for its parameters. If no argument is passed for that parameter
during the function call, the default value will be used.
def greet(name, message="Welcome!"):​
print(f"Hello, {name}! {message}")​

greet("Alice") # message will use the default value​
greet("Bob", "Good morning!") # message is overridden

4.​ Variable Length Argument


In Python, you can pass a variable number of arguments to a function. This is useful when you don't
know how many arguments will be passed to the function. There are two ways to handle
variable-length arguments:

1.​ Arbitrary Positional Arguments (using *args)


def sum_numbers(*args):​
return sum(args)​

print(sum_numbers(1, 2, 3)) # Output: 6​
print(sum_numbers(10, 20, 30, 40)) # Output: 100

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

Write short notes on the following with a suitable example


I) Encapsulation II) Inheritance

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.

Steps for File Handling:


1.​ Opening a File: Use the open() function to open a file in the desired mode.
2.​ Writing to the File: Use write() or writelines() to add data to the file.
3.​ Reading the File: Use read(), readline(), or readlines() to read data from the file.
4.​ Closing the File: Use the close() method to close the file after operations are complete.

# Step 1: Open the file in write mode ('w')​


file = open("P.txt", "w")​

# Step 2: Write data to the file​
file.write("Name: John Doe\n")​
file.write("Father's Name: Robert Doe\n")​

# Step 3: Close the file after writing​
file.close()​

# Step 4: Open the file in read mode ('r') to read its content​
file = open("P.txt", "r")​

# Step 5: Read and print the content of the file​
content = file.read()​
print(content)​

# Step 6: Close the file after reading​
file.close()

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

Steps for the Sieve of Eratosthenes:


1.​ Create a list of consecutive integers from 2 to the given limit (100 in this case).
2.​ Start with the first number (2) and mark all of its multiples as non-prime.
3.​ Move to the next number that is still marked as prime, and mark all of its multiples as non-prime.
4.​ Repeat this process for all numbers up to the square root of the limit.
5.​ The numbers that remain unmarked are prime.

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.

def binary_search(arr, target):​


low = 0​
high = len(arr) - 1​

while low <= high:​
mid = (low + high) // 2 # Find the middle index​
# If target is found at the mid index​
if arr[mid] == target:​
return mid​
# If target is greater, ignore the left half​
elif arr[mid] < target:​
low = mid + 1​
# If target is smaller, ignore the right half​
else:​
high = mid - 1​

# If target is not found​
return -1​

# Example usage​
arr = [12, 14, 41, 43, 62, 65, 91] # Sorted array​
target = 43​
result = binary_search(arr, target)​

if result != -1:​
print(f"Element {target} found at index {result}.")​
else:​
print(f"Element {target} not found.")

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.

Exception handling is a crucial concept in object-oriented programming (OOP) because it allows


developers to manage runtime errors effectively. These errors can be caused by various factors, such as
invalid user input, resource unavailability, or programming mistakes.

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.

Key benefits of exception handling:

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.

In Python, exception handling is done using the following blocks:

●​ try: This block contains code that might raise an exception.


●​ except: This block contains the code that handles the exception if one occurs.
●​ finally: This block contains code that will run regardless of whether an exception occurred or not. It
is typically used for cleanup tasks (like closing files or releasing resources).

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.

def tower_of_hanoi(n, source, destination, auxiliary):​


# Base case: If only one disk is left, move it directly to destination​
if n == 1:​
print(f"Move disk 1 from {source} to {destination}")​
return​

# Move n-1 disks from source to auxiliary, using destination as temporary​
tower_of_hanoi(n - 1, source, auxiliary, destination)​

# Move the nth disk from source to destination​
print(f"Move disk {n} from {source} to {destination}")​

# Move n-1 disks from auxiliary to destination, using source as temporary​
tower_of_hanoi(n - 1, auxiliary, destination, source)​

# Example: Solve Tower of Hanoi for 3 disks​
tower_of_hanoi(3, 'A', 'C', 'B')

SHORT ANSWERS

@rishabh.real
Explain the Programming Cycle for Python in detail.

The programming cycle in Python follows these stages:

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.

Describe the concept of List Slicing with a suitable example.

List Slicing in Python refers to extracting a portion (sub-list) of a list using the slicing syntax

list[start:end:step]

●​ start: The index where the slice begins (inclusive).


●​ end: The index where the slice ends (exclusive).
●​ step: The interval between each element to include in the slice

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]

Show the way to import the module in python.

In Python, you can import modules using the import statement.

import math​
print(math.sqrt(16)) # Output: 4.0

Differentiate between Python Arrays and lists?

@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

More memory-efficient due to contiguous storage Less memory-efficient due to flexibility

Fixed size once created Dynamic size; can grow or shrink as needed

Supports direct arithmetic operations Does not support direct arithmetic operations

Faster for numerical computations Generally slower for numerical operations

Define floor division with an example.

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

Explain the difference between 'append' and 'extend' in Python?

append(): Adds a single element to the end of the list.


my_list = [1, 2, 3]​
my_list.append(4)​
print(my_list) # Output: [1, 2, 3, 4]

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]

What is a dictionary in Python?

A Dictionary in Python is a collection of key-value pairs. Each key must be unique, and values can be of
any data type.

my_dict = {"name": "John", "age": 30, "city": "New York"}​


print(my_dict["name"]) # Output: John

What is Object-Oriented Programming (OOP) in Python? Give an Example

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

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

Explanation: The function count1() counts the number of vowels (both uppercase and lowercase) in the
string 'I love India'.

●​ Vowels in 'I love India' are: I, o, e, I, I, a (6 vowels).

Output: 6

What will be the output of the following code?

list1 = ['M', 'o', 'n', 'k', 'y']​


print("@".join(list1))

M@o@n@k@y

@rishabh.real

You might also like