NEHRU INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
An ISO 9001:2015 and ISO 14001:2015 Certified Institution
Affiliated to Anna University, Chennai, Approved by AICTE, New Delhi &
Recognized by UGC with 2(f) & 12(B), Re-accredited by NAAC “A+”,
NBA Accredited UG Courses: AERO | CSE | ECE | EEE | MECH | MCT
Nehru Gardens, Thirumalayampalayam, Coimbatore – 641 105.
DEPARTMENT OF SCIENCE AND HUMANITIES
B.E. / B. Tech. – Continuous Internal Assessment - III, May 2025
REGULATIONS – 2023 R
COURSE CODE & TITLE: U23GE207 & Problem Solving using Python
Answer Key
Part – A
1. Outline the Object-oriented Programming in Python.
Object-oriented programming (OOP) in Python is a programming paradigm that uses "objects" to
represent data and methods. Key concepts include:
- Classes: Blueprints for creating objects.
- Objects: Instances of classes that encapsulate data and behavior.
- Encapsulation: Bundling data and methods that operate on the data within a class.
- Inheritance: Mechanism to create a new class from an existing class, inheriting attributes and methods.
- Polymorphism: Ability to use a single interface to represent different underlying forms (data types).
2. Summarize about Composition in Python.
Composition in Python is a design principle where a class is composed of one or more objects from
other classes, allowing for a "has-a" relationship. This promotes code reuse and modular design. For
example, a `Car` class may contain an instance of an `Engine` class, indicating that a car "has an" engine.
This allows for better organization and separation of concerns in code.
3. Show the Inheritance with an example.
Inheritance allows a new class (child class) to inherit attributes and methods from an existing class
(parent class).
```python
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def bark(self):
return "Dog barks"
dog = Dog()
print(dog.speak()) # Outputs: Animal speaks
print(dog.bark()) # Outputs: Dog barks
```
4. Interpret the implementation of Networking in Python.
Networking in Python can be implemented using the `socket` module, which provides low-level
networking interfaces. It allows for the creation of client-server applications. For example, a server can
listen for incoming connections, while a client can connect to the server and send/receive data. The `socket`
module supports both TCP and UDP protocols.
5. Define the concept of Client / Server programming in Python.
Page 1 of 10
Client/server programming in Python involves a server that provides resources or services and clients
that request those services. The server listens for incoming connections, processes requests, and sends
responses. Python's `socket` module is commonly used to implement this architecture, enabling
communication over a network.
6. Outline the definition of Class with an example.
A class in Python is a blueprint for creating objects that encapsulate data and methods. It defines
attributes (data) and behaviors (methods) that the objects created from the class will have.
```python
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
return f"{self.make} {self.model}"
my_car = Car("Toyota", "Corolla")
print(my_car.display_info()) # Outputs: Toyota Corolla
```
7. Summarize on creation of Objects with an example.
Creating an object in Python involves instantiating a class, which allocates memory for the object
and initializes its attributes.
```python
class Person:
def __init__(self, name):
self.name = name
# Creating an object
person1 = Person("Alice")
print(person1.name) # Outputs: Alice
```
8. Show the principle of Operator Overloading in Python with an example.
Operator overloading allows custom classes to define the behavior of standard operators. This is
done by defining special methods.
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2 # Uses __add__ method
print(p3.x, p3.y) # Outputs: 4 6
```
9. Interpret the Image processing with its tools.
Image processing in Python can be performed using libraries such as `PIL` (Pillow), `OpenCV`, and
`scikit-image`. These libraries provide tools for opening, manipulating, and saving images. Common tasks
Page 2 of 10
include resizing, filtering, and transforming images. For example, Pillow allows for easy image opening and
manipulation:
```python
from PIL import Image
image = Image.open("example.jpg")
image = image.rotate(90)
image.save("rotated_example.jpg")
```
10. Define Sockets in Python.
Sockets in Python are endpoints for sending and receiving data across a network. The `socket`
module provides a way to create and manage sockets for both client and server applications. Sockets can use
different protocols, such as TCP for reliable communication or UDP for faster, connectionless
communication. Example of creating a socket:
```python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
s.connect(("www.example.com", 80))
Part – B
6.(a)(i) Explore the basics of Image Processing.
Image processing involves manipulating and analyzing images to enhance their quality or extract
useful information.
Types of Image Processing: It can be classified into two main categories:
- Analog Image Processing: Involves processing images in physical form (e.g., photographs).
- Digital Image Processing: Involves manipulating images in digital form using algorithms.
Applications: Common applications include medical imaging, remote sensing, video surveillance, and image
enhancement.
Basic Operations: Fundamental operations include image enhancement (brightness, contrast), filtering
(smoothing, sharpening), and transformations (scaling, rotation).
Image Representation: Images are represented as matrices of pixel values, where each pixel corresponds to a
specific color or intensity.
Tools and Libraries: Various programming libraries, such as OpenCV, Pillow, and scikit-image, facilitate
image processing tasks in Python.
6.(a)(ii) Contrast various Image Processing Tools.
1. OpenCV:
- Strengths: Comprehensive library for computer vision and image processing; supports real-time
applications.
- Use Cases: Object detection, face recognition, and image segmentation.
2. Pillow (PIL):
- Strengths: User-friendly library for basic image manipulation tasks; easy to use for beginners.
- Use Cases: Opening, manipulating, and saving images in various formats.
3. scikit-image:
- Strengths: Built on NumPy and SciPy; provides a collection of algorithms for image processing.
- Use Cases: Image filtering, morphology, and feature extraction.
4. ImageMagick:
- Strengths: Command-line tool for image manipulation; supports a wide range of formats.
- Use Cases: Batch processing of images, format conversion, and image effects.
5. Matplotlib:
Page 3 of 10
- Strengths: Primarily a plotting library, but can also display images and perform basic image processing.
- Use Cases: Visualizing image data and simple transformations.
6. TensorFlow/Keras:
- Strengths: Libraries for deep learning that include image processing capabilities for training models.
- Use Cases: Image classification, object detection, and image generation.
6.(a)(i) Explore the fundamentals to process Images.
1. Image Acquisition: The first step involves capturing images using cameras or sensors, converting them
into a digital format.
2. Preprocessing: This step includes noise reduction, normalization, and resizing to prepare images for
further analysis.
3. Image Enhancement: Techniques such as histogram equalization, contrast stretching, and filtering are
used to improve image quality.
4. Segmentation: The process of partitioning an image into meaningful regions or objects, often using
techniques like thresholding or edge detection.
5. Feature Extraction: Identifying and extracting important features from images, such as edges, corners, or
textures, for analysis.
6. Image Analysis: Applying algorithms to interpret the processed images, which may include classification,
recognition, or measurement tasks.
6.(a)(ii) Contrast the tools to process Images.
1. OpenCV:
- Pros: Extensive functionality for real-time image processing and computer vision.
- Cons: Steeper learning curve for beginners due to its complexity.
2. Pillow (PIL):
- Pros: Simple and intuitive API for basic image manipulation tasks.
- Cons: Limited advanced features compared to OpenCV.
3. scikit-image:
- Pros: Integrates well with NumPy and SciPy; provides a wide range of algorithms.
- Cons: May not be as fast as OpenCV for real-time applications.
4. ImageMagick:
- Pros: Powerful command-line tool for batch processing and format conversion.
- Cons: Requires familiarity with command-line interfaces, which may be challenging for some users.
5. Matplotlib:
- Pros: Excellent for visualizing image data and integrating with data analysis workflows.
- Cons: Limited image processing capabilities compared to dedicated libraries.
6. TensorFlow/Keras:
- Pros: Powerful for deep learning applications involving images; supports GPU acceleration.
- Cons: More complex setup and requires knowledge of machine learning concepts.
6.(b)(i) Illustrate Image File Formats with respect to Python libraries.
1. JPEG (Joint Photographic Experts Group):
- Usage: Widely used for photographs; supports lossy compression.
- Library Support: Supported by Pillow and OpenCV.
2. PNG (Portable Network Graphics):
- Usage: Supports lossless compression and transparency; ideal for web graphics.
- Library Support: Supported by Pillow and OpenCV.
Page 4 of 10
3. GIF (Graphics Interchange Format):
- Usage: Supports animation and transparency; limited to 256 colors.
- Library Support: Supported by Pillow.
4. BMP (Bitmap):
- Usage: Uncompressed format; large file sizes; used in Windows applications.
- Library Support: Supported by Pillow and OpenCV.
5. TIFF (Tagged Image File Format):
- Usage: High-quality images; often used in professional photography and publishing.
- Library Support: Supported by Pillow and OpenCV.
6. WEBP:
- Usage: Modern format that provides lossy and lossless compression; used for web images.
- Library Support: Supported by Pillow and OpenCV.
6.(b)(ii) Demonstrate the algorithms of Classic image processing.
1. Histogram Equalization:
- Purpose: Enhances contrast by redistributing pixel intensity values.
- Algorithm: Calculate the histogram, compute the cumulative distribution function (CDF), and map the
pixel values based on the CDF.
2. Smoothing (Blurring):
- Purpose: Reduces noise and detail in an image.
- Algorithm: Apply a convolution filter (e.g., Gaussian filter) to average pixel values with neighboring
pixels.
3. Edge Detection:
- Purpose: Identifies boundaries within images.
- Algorithm: Use operators like Sobel, Canny, or Laplacian to detect changes in intensity.
4. Thresholding:
- Purpose: Segments an image into foreground and background.
- Algorithm: Convert grayscale images to binary by setting a threshold value; pixels above the threshold
are set to one value, and those below to another.
5. Morphological Operations:
- Purpose: Process images based on their shapes.
- Algorithm: Use operations like dilation and erosion to manipulate the structure of objects in binary
images.
6. Image Filtering:
- Purpose: Enhances or suppresses certain features in an image.
- Algorithm: Apply convolution with various kernels (filters) to achieve effects like sharpening or blurring.
7.(a)(i) Interpret the fundamentals of Networking in context to Python.
Networking refers to the practice of connecting computers and devices to share resources and
communicate over a network.
Protocols: Python supports various networking protocols, including TCP (Transmission Control
Protocol) and UDP (User Datagram Protocol), which are essential for data transmission.
Socket Programming: Python provides the `socket` module, which allows developers to create and
manage network connections using sockets, enabling communication between clients and servers.
Client-Server Architecture: Networking in Python often follows a client-server model, where clients
request services from servers that provide resources or data.
Page 5 of 10
Data Transmission: Python can handle data transmission over networks, including sending and
receiving messages, files, and streams of data.
Libraries and Frameworks: In addition to the `socket` module, Python has libraries like `asyncio` for
asynchronous networking and `Twisted` for event-driven networking, enhancing its capabilities.
7.(a)(ii) Plot the applications of Python program.
Web Development: Python is widely used for building web applications using frameworks like
Django and Flask, enabling rapid development and deployment.
Data Analysis: Libraries like Pandas and NumPy allow for data manipulation and analysis, making
Python a popular choice for data scientists.
Machine Learning: Python's libraries, such as TensorFlow and scikit-learn, facilitate the
development of machine learning models and algorithms.
Automation and Scripting: Python is often used for automating repetitive tasks, such as file
manipulation, web scraping, and system administration.
Game Development: Libraries like Pygame enable developers to create games and interactive
applications using Python.
Networking Applications: Python is used to develop network applications, including chat
applications, file transfer protocols, and web servers.
7.(a)(i) Interpret with python coding for Networking.
```python
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Define the server address and port
server_address = ('localhost', 8080)
# Connect to the server
sock.connect(server_address)
try:
# Send data
message = 'Hello, Server!'
sock.sendall(message.encode())
# Receive response
data = sock.recv(1024)
print('Received:', data.decode())
finally:
sock.close()
```
Explanation:
This code creates a TCP socket, connects to a server at `localhost` on port `8080`, sends a message,
and receives a response.
7.(a)(ii) Plot the usage of python in real-time.
Web Servers: Python is used to create web servers that handle HTTP requests and serve web pages.
RESTful APIs: Python frameworks like Flask and FastAPI are used to build RESTful APIs for web
services.
Real-Time Data Processing: Python can process real-time data streams using libraries like `asyncio`
and `websockets`.
IoT Applications: Python is used in Internet of Things (IoT) applications to communicate with
devices and sensors.
Chat Applications: Python can be used to develop real-time chat applications using WebSocket
protocols.
Network Monitoring Tools: Python scripts can monitor network traffic and performance, providing
insights into network health.
Page 6 of 10
7.(b)(i) Apply the Python programs for Sockets.
```python
import socket
# Create a socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to an address and port
server_socket.bind(('localhost', 8080))
# Listen for incoming connections
server_socket.listen(1)
print("Server is listening on port 8080...")
# Accept a connection
client_socket, client_address = server_socket.accept()
print('Connection from:', client_address)
# Receive data
data = client_socket.recv(1024)
print('Received:', data.decode())
# Send response
client_socket.sendall(b'Hello, Client!')
# Close the sockets
client_socket.close()
server_socket.close()
```
Explanation:
This code creates a simple TCP server that listens for incoming connections, receives data from a
client, and sends a response.
7.(b)(ii) Implement python program for Client / Server model.
Server Code:
```python
import socket
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(1)
print("Server is listening on port 8080...")
client_socket, client_address = server_socket.accept()
print('Connection from:', client_address)
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.sendall(b'Hello, Client!')
client_socket.close()
server_socket.close()
if __name__ == "__main__":
start_server()
```
Client Code:
```python
import socket
Page 7 of 10
def start_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8080))
message = 'Hello, Server!'
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.close()
if __name__ == "__main__":
start_client()
```
Explanation:
The server code listens for connections and responds to a client, while the client code connects to the
server, sends a message, and receives a response. This demonstrates a basic client-server model using
sockets in Python.
Part – C
8.(a)(i) Analyze the basic principles of Object-Oriented Program with Python language.
Encapsulation: OOP allows bundling of data (attributes) and methods (functions) that operate on the
data within a single unit called a class. This restricts direct access to some of the object's
components, promoting data hiding.
Abstraction: OOP enables the creation of abstract classes and interfaces, allowing developers to
define methods that must be implemented in derived classes while hiding complex implementation
details.
Inheritance: This principle allows a new class (child class) to inherit attributes and methods from an
existing class (parent class), promoting code reuse and establishing a hierarchical relationship.
Polymorphism: OOP supports polymorphism, which allows methods to be defined in multiple forms.
This means that a single function name can be used for different types, enabling flexibility in code.
Classes and Objects: Classes serve as blueprints for creating objects, which are instances of classes.
Each object can have its own state and behavior, allowing for modeling real-world entities.
Method Overriding: Child classes can provide specific implementations of methods that are already
defined in their parent classes, allowing for customized behavior while maintaining the same
interface.
8.(a)(ii) Design python program explaining the concept for Class in Python.
```python
class Dog:
def __init__(self, name, age):
self.name = name # Attribute for dog's name
self.age = age # Attribute for dog's age
def bark(self):
return f"{self.name} says Woof!"
def get_age(self):
return f"{self.name} is {self.age} years old."
# Creating an instance of the Dog class
my_dog = Dog("Buddy", 3)
# Using methods of the Dog class
Page 8 of 10
print(my_dog.bark()) # Outputs: Buddy says Woof!
print(my_dog.get_age()) # Outputs: Buddy is 3 years old.
```
Explanation:
This program defines a `Dog` class with attributes for the dog's name and age, along with methods to
make the dog bark and get its age. An instance of the class is created, demonstrating how to use the class.
8.(a)(i) Analyze the python coding with fundamental concepts of Object-Oriented Program.
```python
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
return f"Vehicle: {self.brand} {self.model}"
class Car(Vehicle): # Inheritance
def __init__(self, brand, model, doors):
super().__init__(brand, model) # Call parent constructor
self.doors = doors
def display_info(self): # Method overriding
return f"Car: {self.brand} {self.model}, Doors: {self.doors}"
# Creating an instance of Car
my_car = Car("Toyota", "Corolla", 4)
print(my_car.display_info()) # Outputs: Car: Toyota Corolla, Doors: 4
```
Explanation:
This code demonstrates OOP principles such as inheritance (the `Car` class inherits from `Vehicle`),
method overriding (the `display_info` method is overridden in the `Car` class), and encapsulation (attributes
are encapsulated within classes).
8.(a)(ii) Design the Class in python and explain it.
```python
class Student:
def __init__(self, name, roll_number):
self.name = name # Attribute for student's name
self.roll_number = roll_number # Attribute for roll number
def display_details(self):
return f"Student Name: {self.name}, Roll Number: {self.roll_number}"
# Creating an instance of the Student class
student1 = Student("Alice", 101)
# Using the method to display student details
print(student1.display_details()) # Outputs: Student Name: Alice, Roll Number: 101
```
- Explanation:
The `Student` class has attributes for the student's name and roll number, and a method to display
these details. This encapsulates the data and behavior related to a student, demonstrating the concept of a
class in OOP.
8.(b)(i) Construct a Python program for creation of Objects and its utilization.
```python
class Book:
Page 9 of 10
def __init__(self, title, author):
self.title = title
self.author = author
def get_info(self):
return f"'{self.title}' by {self.author}"
# Creating objects of the Book class
book1 = Book("1984", "George Orwell")
book2 = Book("To Kill a Mockingbird", "Harper Lee")
# Utilizing the objects
print(book1.get_info()) # Outputs: '1984' by George Orwell
print(book2.get_info()) # Outputs: 'To Kill a Mockingbird' by Harper Lee
```
Explanation:
This program defines a `Book` class and creates two objects representing different books. The
`get_info` method is used to retrieve and display information about each book.
8.(b)(ii) Develop an example for Operator Overloading in Python.
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # Overloading the + operator
return Point(self.x + other.x, self.y + other.y)
def __str__(self): # String representation of the object
return f"Point({self.x}, {self.y})"
# Creating Point objects
point1 = Point(2, 3)
point2 = Point(5, 7)
# Using operator overloading
result_point = point1 + point2 # Calls the __add__ method
print(result_point) # Outputs: Point(7, 10)
```
Explanation:
This example demonstrates operator overloading by defining the `__add__` method in the `Point`
class, allowing the use of the `+` operator to add two `Point` objects. The `__str__` method provides a
readable string representation of the object.
Page 10 of 10