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

OOP Using Python (1)

Uploaded by

Manasveer Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

OOP Using Python (1)

Uploaded by

Manasveer Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Solution-MTE

SECTION-A

Answer: (d.) F7A49T1H7

Answer: 4
Answer: 15

SECTION-B
B1. Explain why tuples can be more efficient in terms of memory and performance
compared to lists. Provide a scenario where using tuple instead of a list would be
beneficial. Analyse the differences between Python’s collection types—Lists, Tuples, Sets,
and Dictionaries.
[ Any one scenario + Differences =2+2]
Answer:
When it comes to choosing between lists and tuples, consider the following:
 Memory Efficiency: Tuples are more memory-efficient than lists due to
their immutability and fixed size.
 Use Cases: We use tuples when you need a simple collection of items that
should not change throughout the program. Lists are preferable when you need a
mutable collection that can be modified dynamically.
Real-Life Examples of Memory Optimization Using Tuples Over Lists:
1. High-Frequency Trading Systems: In financial trading systems where millisecond-
level latency is crucial, tuples can be used to store trade data such as timestamps, stock
symbols, and prices. By using tuples, these systems can reduce memory overhead and
improve the performance of data processing.
# Example of trade data tuple
trade = (1632324825, "AAPL", 150.35)
2. Scientific Computing and Machine Learning: In scientific computing, where
large datasets are processed, tuples can be used to store fixed feature sets in machine
learning models. This reduces memory usage when handling vast datasets in memory
and speeds up the processing time.
# Example of feature tuple in a dataset
feature_tuple = (1.5, 2.3, 3.8)

3.Logging and Event Tracking Systems: In systems that log events or track user
actions, tuples can be used to represent each log entry or action as an immutable data
point. This is particularly useful in distributed systems, where immutability ensures
consistency and reduces memory overhead.
# Example of a log entry tuple
log_entry = (1623839222, "INFO", "User logged in")
4.Embedded Systems and IoT Devices: In embedded systems and IoT devices,
where memory is a constrained resource, using tuples to store sensor readings or
configuration settings can optimize memory usage and extend device battery life by
reducing the computational load.
# Example of a sensor reading tuple
sensor_reading = (1623839222, "temperature", 72.5)

Feature List Tuple Set Dictionary


Ordered Yes Yes No Yes
Yes Yes (Can
No (Immutable Yes (Values can
Mutable (Elements can add/remove
after creation) be changed)
be changed) elements)
Keys: No,
Allows Duplicates Yes Yes No
Values: Yes
Keys: No,
Indexing & Slicing Yes Yes No
Values: Yes
Yes (for values;
Heterogeneous
Yes Yes Yes keys must be
Elements
unique)
Fast for
Fast lookup by
Slower than membership
Iteration Speed Faster than list key (hash-
tuple tests (hash-
based)
based)
Key-Value Pairs No No No Yes
Hashable (Can be
No (unless No (unless No (but keys
used as a key in a Yes
frozenset) frozenset) are hashable)
dictionary or set)
General-
Fast
purpose, Fixed-size Lookup table,
membership
Use Case dynamic- data, read-only mapping keys
testing,
sized collections to values
uniqueness
collection
Higher due to Higher (due to
Efficient for
dynamic Lower due to hashing and
Memory Usage storing unique
resizing immutability key-value
items
overhead storage)
Extensive Extensive
Limited Extensive
(append(), (add(),
Methods Available (count(), (get(), keys(),
remove(), remove(),
index()) values())
etc.) union())
B2. Write a python program to construct the below pattern.
1
121
12321
1234321
12321
121
1

Answer:
def print_pattern(n):
# Upper part of the pattern (including the middle row)
for i in range(1, n+1):
# First half numbers
for j in range(1, i+1):
print(j, end=" ")
# Second half numbers (in reverse)
for j in range(i-1, 0, -1):
print(j, end=" ")
print() # Move to the next line

# Lower part of the pattern


for i in range(n-1, 0, -1):
# First half numbers
for j in range(1, i+1):
print(j, end=" ")
# Second half numbers (in reverse)
for j in range(i-1, 0, -1):
print(j, end=" ")
print() # Move to the next line

# Number of rows for the middle section (you can change n to generate larger patterns)
n=4
print_pattern(n)
Output:
1
121
12321
1234321
12321
121
1
B3. (a.) What is a lambda function in Python, and how does it differ from a
regular function?
Write a lambda function to filter out even numbers from a given list.
Answer:
A lambda function in Python is a small, anonymous function that is defined using the
lambda keyword. It can take any number of arguments but only has one expression. The
expression is evaluated and returned when the function is called. Lambda functions are
typically used for short, simple operations and are often used in situations where a full
function definition would be overkill, such as in functional programming paradigms like
map(), filter(), or reduce().
Key Differences Between Lambda and Regular Functions:

Feature Lambda Function Regular Function


Defined using the lambda
Definition Defined using the def keyword
keyword
Yes, usually unnamed (though it
Anonymous No, always named
can be assigned)
Number of Can have multiple expressions
Can only have one expression
Expressions and statements
Implicitly returns the result of the Explicit return statement is
Return
expression required
Best for more complex logic or
Use Case Best for short, simple operations
multi-line tasks
Example of Lambda Function Syntax:
lambda arguments: expression
Lambda Function Example: Filter Even Numbers from a List
Here's how to use a lambda function with the filter() function to filter out even numbers
from a list:
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Lambda function to filter even numbers
even_numbers = list (filter(lambda x: x % 2 == 0, numbers))
# Output the filtered list of even numbers
print(even_numbers)

B3. (b.) Differentiate iterator with recursion? Write a program to print the 1 to 100
Fibonacci
series using recursive function?
Answer:
(b) Difference Between Iteration and Recursion
Feature Iteration Recursion
Iteration is the process of Recursion is a method where a function
Definition repeating a set of instructions calls itself to solve a smaller instance of
using loops like for or while. the same problem.
Feature Iteration Recursion
Maintains state using loop
State Each recursive call creates a new
control variables that change
Retention instance with its own local state.
with each iteration.
Controlled using loop
Terminates when a base case is reached,
Termination conditions (e.g., for or while
or else may lead to infinite recursion.
loop condition).
Memory-efficient, uses the Uses more memory because each
Memory
same memory space recursive call adds a new frame to the
Usage
throughout the loop. call stack.
Typically faster because it Slower due to the overhead of multiple
Speed avoids the overhead of function calls and the associated
multiple function calls. memory management.
Best for repetitive tasks over Best suited for problems that can be
Use Case data structures (like traversing divided into smaller subproblems (e.g.,
arrays, lists). tree traversal, factorial).
Sometimes more readable for problems
Easier to understand for
Readability like divide and conquer, though complex
simple repetitive tasks.
recursion can be harder to follow.

Program:
def fibonacci_recursive(a, b):
# Base case: Stop if the next number exceeds 100
if a > 100:
return
print(a, end=" ")
fibonacci_recursive(b, a + b)
# Start the Fibonacci sequence with 1 and 1
fibonacci_recursive(1, 1)

B4. Write a Python function named "count_consonants" that takes a string as


input and
counts the number of consonants present in the string. The function should use
a for loop
to iterate over each character in the string and use an if statement to check if
the character
is a consonant. The function should return the total count of consonant found.

Answer:
def count_consonants(input_string):
# Initialize a counter for consonants
consonant_count = 0

# Convert the input string to lowercase to handle case insensitivity


input_string = input_string.lower()
# Define vowels for checking consonants
vowels = 'aeiou'

# Iterate over each character in the input string


for char in input_string:
# Check if the character is an alphabet and not a vowel (i.e., a consonant)
if char.isalpha() and char not in vowels:
consonant_count += 1

return consonant_count

# Example usage:
text = "Manipal"
print(f"Number of consonants: {count_consonants(text)}")

Output: 4

SECTION-C
(a.) Give answers of the following:
1. Explain the uses of *args and **kwargs with syntax.
2. Create a Python class named Circle constructed by a radius and two
methods
which will compute the area and the perimeter of a circle.
Answer:

(1.)

In Python, *args and **kwargs are used to pass a variable number of arguments to a
function. These allow for flexible function definitions where the exact number of
arguments is not predetermined.

1. *args: Passing Variable Number of Positional Arguments


 Definition: *args allows a function to accept any number of positional arguments.
It collects all the extra positional arguments passed to the function and packs them
into a tuple.
 Use Case: Use *args when you want to create a function that can handle more
arguments than initially specified.

def print_numbers(*args):
for number in args:
print(number) # Calling the function with varying number of arguments
print_numbers(1, 2, 3)
print_numbers(10, 20, 30, 40, 50)

2. **kwargs: Passing Variable Number of Keyword Arguments


 Definition: **kwargs allows a function to accept any number of keyword
arguments (arguments passed as key-value pairs). It collects these into a
dictionary.
 Use Case: Use **kwargs when you want to allow the function to accept a variable
number of named arguments.

def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}") # Calling the function with varying keyword
arguments print_details(name="Robert",age=30,profession="Professor")
print_details(name="John", age=25, city="New York")

Output:
name: Robert age: 30 profession: Professor
name: John age: 25 city: New York

(2.) Create a Python class named Circle constructed by a radius and two
methods
which will compute the area and the perimeter of a circle.

Answer:
import math # Importing math module to access the value of pi

class Circle:
# Constructor to initialize the radius of the circle
def __init__(self, radius):
self.radius = radius

# Method to calculate the area of the circle


def compute_area(self):
return math.pi * (self.radius ** 2)

# Method to calculate the perimeter (circumference) of the circle


def compute_perimeter(self):
return 2 * math.pi * self.radius

# Example usage of the Circle class


circle = Circle(5) # Creating an instance of Circle with radius 5

# Computing and displaying the area and perimeter


print(f"Area of the circle: {circle.compute_area():.2f}")
print(f"Perimeter of the circle: {circle.compute_perimeter():.2f}")
C1. (b.) What are decorators? analyse how decorators promote code reusability
and separation of concerns by evaluating a scenario where a logging decorator
is applied to multiple functions in an application.
Answer:

In Python, decorators are a powerful and flexible tool that allows you to modify or
extend the behavior of a function or method without changing its actual code. A decorator
is essentially a function that takes another function as an argument, adds some
functionality to it, and returns a new function with the enhanced behavior.
Decorators are often used to implement cross-cutting concerns like logging,
authentication, and input validation, which are needed in many parts of an application,
but should be kept separate from the business logic of individual functions. This leads to
code reusability and separation of concerns.

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
# Add extra functionality here
return original_function(*args, **kwargs)
return wrapper_function

@decorator_function
def some_function():
print("This is the original function.")

Scenario: Logging Decorator


In this scenario, we want to apply logging to multiple functions in an application to track
when the functions are called, what arguments they receive, and what their results are.
This can be achieved by using a logging decorator.

def logging_decorator(func):
def wrapper(*args, **kwargs):
# Log the function name and the arguments passed
print(f"Calling function '{func.__name__}' with arguments {args} and keyword
arguments {kwargs}")

# Call the original function and store the result


result = func(*args, **kwargs)

# Log the result of the function


print(f"Function '{func.__name__}' returned {result}")

# Return the result of the original function


return result
return wrapper

# Applying the logging decorator to different functions

@logging_decorator
def add(a, b):
return a + b

@logging_decorator
def multiply(a, b):
return a * b

@logging_decorator
def greet(name):
return f"Hello, {name}!"

# Example usage
add(3, 4)
multiply(2, 5)
greet("Bhavana")
Output:
javascript
Copy code
Calling function 'add' with arguments (3, 4) and keyword arguments {}
Function 'add' returned 7
Calling function 'multiply' with arguments (2, 5) and keyword arguments {}
Function 'multiply' returned 10
Calling function 'greet' with arguments ('Bhavana',) and keyword arguments {}
Function 'greet' returned Hello, Bhavana!

Real-World Use Case:


In a larger application, decorators like the logging decorator can be applied to multiple
functions across different modules to keep track of their execution without modifying
their internal logic. This can be especially useful in:
 Debugging: Automatically log function calls to troubleshoot issues.
 Monitoring: Keep track of how often certain functions are invoked.
 Security: Use decorators to check for authentication before executing a function
(e.g., in web applications).

--------------------------------------------------------------------------------------------------------------

You might also like