OOP Using Python (1)
OOP Using Python (1)
SECTION-A
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)
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
# 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:
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)
Answer:
def count_consonants(input_string):
# Initialize a counter for consonants
consonant_count = 0
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.
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
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.")
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}")
@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!
--------------------------------------------------------------------------------------------------------------