0% found this document useful (0 votes)
13 views33 pages

Python DSA Programs

Project

Uploaded by

Akash Mane
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views33 pages

Python DSA Programs

Project

Uploaded by

Akash Mane
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 33

JSPM's

JAYAWANTRAO SAWANT COLLEGE OF ENGINEERING


MCA Department
For Academic Year 2024-25

IT-11L Practical
Python Programming
And
Data Structure and Algorithms
(2024 Pattern)

Prepared By:
Nikita Ramchandra Mane
MCA FIRST YEAR (Sem I)
Roll No- 40
CERTIFICATE

This is to certify that Miss. Pranjali Popat Shinde, MCA I Year is a

bonafide student of Jayawantrao Sawant College of Engineering, Hadapsar,

Pune-28. She has successfully completed the practical work in the subject

Python Programming and Data structure and Algorithms (IT-11L) as per the

guidelines provided by Savitribai Phule Pune University for Academic Year

2024-25.

Subject Teacher Prof. Swayam Shah


1] Prof. Savitri Pradhan HOD
2] Prof. Krutika Kakpure

Internal Examiner External Examiner

Date: / /2024

Place: Pune
INDEX
Python Programs

1. Write a program to check if the input number is a palindrome or not.


Input:

num = input("Enter a number: ")

if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

Output:

2. Write a program to create a Class called “Bank” having the following


attributes:
bank_name,branch,city,manager_name and use constructor to initialize
the above attributes of class. and also write following methods in the
class change_manager name – to modify manager name
display_details – to print the values of above attributes.
Input:

class Bank:
def __init__(self, bank_name, branch, city, manager_name):
self.bank_name = bank_name
self.branch = branch
self.city = city
self.manager_name = manager_name

def change_managername(self, new_manager_name):


self.manager_name = new_manager_name

def display_details(self):
print("\nBank Details:")
print(f"Bank Name: {self.bank_name}")
print(f"Branch: {self.branch}")
print(f"City: {self.city}")
print(f"Manager Name: {self.manager_name}")

# Input from user


bank_name = input("Enter Bank Name: ")
branch = input("Enter Branch: ")
city = input("Enter City: ")
manager_name = input("Enter Manager Name: ")
# Create Bank object
bank = Bank(bank_name, branch, city, manager_name)

# Display details
bank.display_details()

# Update manager name if needed


new_manager_name = input("\nEnter new Manager Name: ")
if new_manager_name:
bank.change_managername(new_manager_name)

# Display updated details


bank.display_details()

Output:

3. Write a program to demonstrate a method overriding in derived class


from base class.
Input:

# Base class
class Animal:
def sound(self):
print("This animal makes a sound.")

# Derived class
class Dog(Animal):
def sound(self):
print("The dog barks.")

# Another derived class


class Cat(Animal):
def sound(self):
print("The cat meows.")

# Demonstration of method overriding


animal = Animal()
dog = Dog()
cat = Cat()

# Call the sound method on each object


print("Base class method:")
animal.sound()
print("\nOverridden methods in derived classes:")
dog.sound()
cat.sound()
Output:

4. Write a program to show how multithreading works, where a thread


checks a number is even or odd, and another thread checks if the same
number is prime or not.
Input:

import threading

# Function to check if a number is even or odd


def check_even_odd(number):
if number % 2 == 0:
print(f"{number} is Even.")
else:
print(f"{number} is Odd.")

# Function to check if a number is prime


def check_prime(number):
if number <= 1:
print(f"{number} is not Prime.")
return
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
print(f"{number} is not Prime.")
return
print(f"{number} is Prime.")

# Input from the user


number = int(input("Enter a number: "))

# Create threads
thread1 = threading.Thread(target=check_even_odd, args=(number,))
thread2 = threading.Thread(target=check_prime, args=(number,))

# Start threads
thread1.start()
thread2.start()

# Wait for threads to complete


thread1.join()
thread2.join()

print("Multithreading task completed.")

Output:
5. Write a program to overload “==” operator.
Input:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __eq__(self, other):


"""Overload the '==' operator to compare two Person
objects."""
if not isinstance(other, Person):
return False
# Compare both name and age for equality
return self.name == other.name and self.age == other.age

# Example usage
person1 = Person("Anu", 30)
person2 = Person("Anu", 30)
person3 = Person("Sanu", 25)

print(person1 == person2) # True (same name and age)


print(person1 == person3) # False (different name or age)

Output:

6. Write a program to show different types of constructors in a class with


example invocations.
Input:

class MyClass:
# Constructor with default argument
def __init__(self, name="Default"):
self.name = name

# Creating objects using different constructors


obj1 = MyClass() # Calls the constructor with the default argument
obj2 = MyClass("Parameterized") # Calls the constructor with the
parameterized argument

print(obj1.name) # Output: Default


print(obj2.name) # Output: Parameterized

Output:
7. Write a program to create an employees collection in a mongodb
database and perform CRUD operations on this collection.
Input:

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/") # Replace with
your MongoDB URI if needed
db = client["company_database"] # Create or connect to a database
collection = db["employees"] # Create or connect to the employees
collection

# 1. Create - Inserting new employees into the collection


def create_employee():
employee_data = {
"name": "Diya",
"age": 21,
"department": "MCA",
"salary": 60000
}
# Insert a single document
result = collection.insert_one(employee_data)
print(f"Employee added with ID: {result.inserted_id}")

# 2. Read - Fetching employee data


def read_employee():
print("\nFetching employee details with name 'Diya'...")
# Find one employee with the name "John Doe"
employee = collection.find_one({"name": "Diya"})
if employee:
print(employee)
else:
print("Employee not found.")

# 3. Update - Updating employee details


def update_employee():
print("\nUpdating employee details...")
result = collection.update_one(
{"name": "Diya"}, # Query
{"$set": {"salary": 65000}} # Update operation
)
if result.matched_count > 0:
print(f"Updated {result.matched_count} document(s).")
else:
print("No matching employee found to update.")
# 4. Delete - Deleting an employee
def delete_employee():
print("\nDeleting employee with name 'Diya'...")
result = collection.delete_one({"name": "Diya"})
if result.deleted_count > 0:
print("Employee deleted.")
else:
print("Employee not found.")

# Perform the CRUD operations


def perform_crud_operations():
# Create
create_employee()

# Read
read_employee()

# Update
update_employee()

# Read again after update


read_employee()

# Delete
delete_employee()

# Try reading again after deletion


read_employee()

# Run CRUD operations


perform_crud_operations()

Output:

8. Write a program to accept a integer and use try/except to catch


exception if a floating point number is entered.
Input:

try:
# Accept input from the user
user_input = input("Enter an integer: ")

# Try to convert the input to an integer


number = int(user_input)

print(f"You entered the integer: {number}")

except ValueError:
# This block will run if the input is not an integer (e.g., a float or
non-numeric input)
print("Error: You entered a floating-point number or invalid input.
Please enter a valid integer.")
Output:

9. Write a program to print the Fibonacci series up to a given number of


terms, using while loop and recursive approaches.
Input:

Using While Loop:


def fibonacci_while(n):
a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1

# Get the number of terms from the user


num_terms = int(input("Enter the number of terms for
Fibonacci series (using while loop): "))
print("Fibonacci series using while loop:")
fibonacci_while(num_terms)
Output:

Input:

Using Recursive:
def fibonacci_recursive(n, a=0, b=1, count=0):
if count < n:
print(a, end=" ")
fibonacci_recursive(n, b, a + b, count + 1)

# Get the number of terms from the user


num_terms = int(input("\nEnter the number of terms for
Fibonacci series (using recursion): "))
print("Fibonacci series using recursion:")
fibonacci_recursive(num_terms)
Output:
10. What is multiple inheritance, write a program to show multiple
inheritance using super().
Multiple Inheritance in Python

Multiple inheritance is a feature in Python where a class can inherit


attributes and methods from more than one parent class. This allows
a child class to inherit properties and behaviors from multiple classes,
which can be useful for code reuse and extending functionalities.
In Python, when you use multiple inheritance, the super() function
can help call methods from parent classes, especially in cases where
the class hierarchy is more complex.

Input:

class Parent1:
def __init__(self):
print("Parent1 constructor called")

def greet(self):
print("Hello from Parent1!")

class Parent2:
def __init__(self):
print("Parent2 constructor called")

def greet(self):
print("Hello from Parent2!")

class Child(Parent1, Parent2):


def __init__(self):
super().__init__() # Call the constructor of the first parent class
in the MRO
print("Child constructor called")

def greet(self):
super().greet() # Call the greet method of the first parent in the
MRO
print("Hello from Child!")

# Create an instance of the Child class


child = Child()

# Call the greet method from the child class


child.greet()
Output:
11. What is thread synchronization, write a program to show the same
using commit and rollback.
Thread Synchronization

Thread synchronization is a concept used in multithreading


programming to ensure that multiple threads can safely share
resources (such as variables or files) without causing conflicts or
inconsistencies. Without synchronization, threads may
simultaneously modify shared resources, leading to data corruption
or unexpected results.

Input:

import threading

class BankAccount:

def __init__(self, balance):

self.balance = balance

self.lock = threading.Lock() # Lock for synchronization

# Method to perform commit (add money)

def commit(self, amount):

with self.lock: # Synchronize the commit action

print(f"Committed: Adding {amount} to balance.")

self.balance += amount

print(f"New balance after commit: {self.balance}")

# Method to perform rollback (subtract money)

def rollback(self, amount):

with self.lock: # Synchronize the rollback action

print(f"Rolled back: Subtracting {amount} from balance.")

self.balance -= amount

print(f"New balance after rollback: {self.balance}")

# Create a BankAccount instance with initial balance

account = BankAccount(1000)
# Function to simulate commit thread

def commit_thread():

account.commit(200)

# Function to simulate rollback thread

def rollback_thread():

account.rollback(100)

# Create threads for commit and rollback

thread1 = threading.Thread(target=commit_thread)

thread2 = threading.Thread(target=rollback_thread)

# Start the threads

thread1.start()

thread2.start()

# Wait for both threads to complete

thread1.join()

thread2.join()

print(f"Final balance: {account.balance}")

Output:

12. Develop a web application using Django framework.


Input:

Output:

13. Write a program to count the number of upper-case, lower-case, special


character and numeric values using Regular expressions in python.
Input:

import re

# Function to count characters using regular expressions


def count_characters(input_string):
# Regular expressions to match different types of characters
uppercase = re.findall(r'[A-Z]', input_string) # Match all
uppercase letters
lowercase = re.findall(r'[a-z]', input_string) # Match all lowercase
letters
digits = re.findall(r'[0-9]', input_string) # Match all digits
special_chars = re.findall(r'[^A-Za-z0-9]', input_string) # Match
all non-alphanumeric characters

# Return the counts


return len(uppercase), len(lowercase), len(digits),
len(special_chars)

# Input from the user


input_string = input("Enter a string: ")

# Get the counts of uppercase, lowercase, digits, and special


characters
uppercase_count, lowercase_count, digits_count,
special_chars_count = count_characters(input_string)

# Display the result


print(f"Uppercase letters: {uppercase_count}")
print(f"Lowercase letters: {lowercase_count}")
print(f"Digits: {digits_count}")
print(f"Special characters: {special_chars_count}")
Output:

14. Write a program to validate an input string is URL or not using regular
expression and explain the meaning of each special characters of the
regular expression you have used.
Input:

import re

# Function to validate URL using regular expression


def validate_url(url):
# Regular expression pattern to validate URL
pattern = re.compile(r'^(https?://)?([a-zA-Z0-9-]+\.)+[a-zA- Z]
{2,6}(/[\w\-./?%&=]*)?$')

# Match the URL with the pattern


if pattern.match(url):
return True
else:
return False

# Input from the user


url = input("Enter a URL: ")
# Validate and display the result
if validate_url(url):
print("Valid URL")
else:
print("Invalid URL")
Output:

15. Write a program to interchange the first and last element in a list.
Input:

def interchange_first_last(lst):
# Check if the list has more than one element
if len(lst) > 1:
# Swap the first and last elements
lst[0], lst[-1] = lst[-1], lst[0]
return lst

# Example usage
my_list = [10, 20, 30, 40, 50]
print("Original list:", my_list)

# Interchange first and last elements


modified_list = interchange_first_last(my_list)
print("Modified list:", modified_list)
Output:
Data Structure and Algorithm Programs

1. Write a python program for how to create and manipulate arrays.


Input:

import numpy as np

# Create a 1D array
array = np.array([10, 20, 30, 40, 50])
print("Original Array:", array)

# Accessing elements
print("First Element:", array[0])
print("Last Element:", array[-1])

# Modify an element
array[2] = 99
print("Modified Array:", array)

# Adding a value to each element


new_array = array + 5
print("Array After Adding 5:", new_array)

# Finding the maximum and minimum values


print("Maximum Value:", array.max())
print("Minimum Value:", array.min())

# Slicing the array


print("First Three Elements:", array[:3])

Output:

2. Write a python program to perform basic operations such as insertion, deletion,


and traversal in 1D array.
Input:

# Importing the array module


import array

# Create a 1D array
arr = array.array('i', [10, 20, 30, 40, 50]) # 'i' for integers
print("Original Array:", arr)

# Traversal: Print each element


print("\nTraversing the Array:")
for item in arr:
print(item)

# Insertion: Add an element at a specific position


arr.insert(2, 25) # Insert 25 at index 2
print("\nArray after Insertion:", arr)

# Deletion: Remove an element by value


arr.remove(40) # Remove the element with value 40
print("\nArray after Deletion:", arr)

Output:

3. Write a python program for implementing a function that searches for an element
in a 1-D array and returns its index.
Input:

# Function to search for an element in an array


def search_element(arr, target):
if target in arr:
return arr.index(target) # Return the index of the target
else:
return -1 # Return -1 if the target is not found

# Example usage
my_array = [10, 20, 30, 40, 50]
print("Array:", my_array)

# Search for an element


element_to_search = 30
result = search_element(my_array, element_to_search)

# Print the result


if result != -1:
print(f"Element {element_to_search} found at index {result}.")
else:
print(f"Element {element_to_search} not found in the array.")

Output:
4. Write a python program for how to represent and manipulate sparse matrices.
Input:

import numpy as np
from scipy.sparse import csr_matrix

# Create a dense matrix


dense_matrix = np.array([
[0, 0, 0, 5],
[0, 8, 0, 0],
[0, 0, 3, 0],
[6, 0, 0, 0]
])
print("Dense Matrix:\n", dense_matrix)

# Convert the dense matrix to a sparse matrix


sparse_matrix = csr_matrix(dense_matrix)
print("\nSparse Matrix:\n", sparse_matrix)

# Display non-zero elements of the sparse matrix


print("\nNon-zero elements:", sparse_matrix.data)

# Convert sparse matrix back to a dense matrix


dense_again = sparse_matrix.toarray()
print("\nConverted Back to Dense Matrix:\n", dense_again)

Output:

5. Write a python function that reverses a string using an array.


Input:

def reverse_string(input_string):
# Create an empty array to store the reversed string
reversed_array = []

# Traverse the string from the end to the start and append characters to the
array
for char in input_string:
reversed_array.insert(0, char)

# Join the array back into a string


reversed_string = ''.join(reversed_array)

return reversed_string

# Example usage
input_string = input(“Enter a String:”)
reversed_string = reverse_string(input_string)
print("Reversed String:", reversed_string)

Output:

6. Write a python program for singly linked list- To create linked list and display it.
Input:

# Define the Node class


class Node:
def __init__(self, data):
self.data = data # Store data in the node
self.next = None # Pointer to the next node (initially None)

# Define the LinkedList class


class LinkedList:
def __init__(self):
self.head = None # Initially the linked list is empty

# Function to add a node to the linked list


def append(self, data):
new_node = Node(data) # Create a new node
if self.head is None: # If the list is empty, make new_node the head
self.head = new_node
else:
last_node = self.head
while last_node.next: # Traverse the list to find the last node
last_node = last_node.next
last_node.next = new_node # Make the last node point to new_node

# Function to display the linked list


def display(self):
current = self.head # Start with the head of the list
while current: # Traverse until the end of the list
print(current.data, end=" -> ")
current = current.next # Move to the next node
print("None") # Print "None" to indicate the end of the list

# Example usage
linked_list = LinkedList() # Create a new linked list
linked_list.append(10) # Add nodes
linked_list.append(20)
linked_list.append(30)

# Display the linked list


linked_list.display()

Output:

7. Write a python program for singly linked list to search given data in linked list.
Input:

class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
else:
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node

def search(self, data):


current = self.head
while current:
if current.data == data:
return True
current = current.next
return False

# Example usage
linked_list = LinkedList()
linked_list.append(10)
linked_list.append(20)
linked_list.append(30)

# Search for data in the linked list


print(linked_list.search(20)) # True
print(linked_list.search(40)) # False

Output:
8. Write a Python program for doubly linked list to insert node at last position of
linked list.
Input:

# Define the Node class


class Node:
def __init__(self, data):
self.data = data # Store the data
self.next = None # Pointer to the next node
self.prev = None # Pointer to the previous node

# Define the Doubly Linked List class


class DoublyLinkedList:
def __init__(self):
self.head = None # Initially the list is empty

# Function to insert a node at the last position


def insert_last(self, data):
new_node = Node(data) # Create a new node
if self.head is None: # If the list is empty, the new node is the
head
self.head = new_node
else:
temp = self.head
while temp.next: # Traverse to the last node
temp = temp.next
temp.next = new_node # Link the last node to the new node
new_node.prev = temp # Link the new node back to the last
node

# Function to display the linked list


def display(self):
temp = self.head
while temp:
print(temp.data, end=" <-> ")
temp = temp.next
print("None")

# Example usage
dll = DoublyLinkedList() # Create an empty doubly linked list

dll.insert_last(10) # Insert at the last position


dll.insert_last(20)
dll.insert_last(30)

dll.display() # Display the linked list

Output:
9. Write a Python program for doubly linked list to delete a node from specified
position.
Input:

class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class DoublyLinkedList:
def __init__(self):
self.head = None

# Function to insert a node at the end of the list


def insert_last(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
new_node.prev = temp

# Function to delete a node at a specified position


def delete_at_position(self, position):
if self.head is None:
print("List is empty.")
return

temp = self.head
# If position is 0, delete the head
if position == 0:
self.head = temp.next
if self.head:
self.head.prev = None
temp = None
return

# Traverse to the desired position


for _ in range(position):
temp = temp.next
if not temp:
print("Position out of bounds.")
return
# Remove the node
if temp.next:
temp.next.prev = temp.prev
if temp.prev:
temp.prev.next = temp.next
temp = None

# Function to display the list


def display(self):
temp = self.head
while temp:
print(temp.data, end=" <-> ")
temp = temp.next
print("None")

# Example usage
dll = DoublyLinkedList()
dll.insert_last(10)
dll.insert_last(20)
dll.insert_last(30)
dll.insert_last(40)

print("Original List:")
dll.display()

# Delete node at position 2 (which is 30)


dll.delete_at_position(2)

print("List after deletion at position 2:")


dll.display()

Output:

10. Write a python program to create a singly linked list and count total number of
nodes in it and display the result.
Input:

# Define the Node class


class Node:
def __init__(self, data):
self.data = data # Store the data
self.next = None # Pointer to the next node

# Define the SinglyLinkedList class


class SinglyLinkedList:
def __init__(self):
self.head = None # Initially, the list is empty

# Function to insert a node at the end of the list


def append(self, data):
new_node = Node(data) # Create a new node
if not self.head: # If the list is empty
self.head = new_node
else:
temp = self.head
while temp.next: # Traverse to the last node
temp = temp.next
temp.next = new_node # Link the last node to the new node

# Function to count the total number of nodes in the list


def count_nodes(self):
count = 0
temp = self.head
while temp:
count += 1
temp = temp.next
return count

# Function to display the linked list


def display(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None") # Indicating the end of the list

# Example usage
sll = SinglyLinkedList() # Create an empty singly linked list

# Insert nodes
sll.append(10)
sll.append(20)
sll.append(30)
sll.append(40)

# Display the linked list


print("Singly Linked List:")
sll.display()

# Count the number of nodes


total_nodes = sll.count_nodes()

# Display the total number of nodes


print(f"Total number of nodes: {total_nodes}")

Output:
11. Write a Python program for doubly linked list to sort the linked list in ascending
order.
Input:

# Define the Node class


class Node:
def __init__(self, data):
self.data = data # Store the data
self.next = None # Pointer to the next node
self.prev = None # Pointer to the previous node

# Define the DoublyLinkedList class


class DoublyLinkedList:
def __init__(self):
self.head = None # Initially, the list is empty

# Function to insert a node at the end of the list


def insert_last(self, data):
new_node = Node(data) # Create a new node
if not self.head: # If the list is empty
self.head = new_node
else:
temp = self.head
while temp.next: # Traverse to the last node
temp = temp.next
temp.next = new_node # Link the last node to the new node
new_node.prev = temp # Link the new node back to the last node

# Function to display the linked list


def display(self):
temp = self.head
while temp:
print(temp.data, end=" <-> ")
temp = temp.next
print("None")

# Function to sort the list in ascending order (using a simple bubble sort)
def sort_ascending(self):
if not self.head: # If the list is empty
return

temp = self.head
while temp:
current = temp
while current and current.next:
if current.data > current.next.data:
# Swap the data of the two nodes
current.data, current.next.data = current.next.data, current.data
current = current.next
temp = temp.next
# Example usage
dll = DoublyLinkedList() # Create an empty doubly linked list

# Insert nodes
dll.insert_last(40)
dll.insert_last(10)
dll.insert_last(30)
dll.insert_last(20)

print("Original List:")
dll.display()

# Sort the list in ascending order


dll.sort_ascending()

print("Sorted List in Ascending Order:")


dll.display()

Output:

12. Write a Python program for binary search tree creation and insertion of elements.
Input:

# Define the Node class for the BST


class Node:
def __init__(self, data):
self.data = data # Store the value of the node
self.left = None # Pointer to the left child
self.right = None # Pointer to the right child

# Define the Binary Search Tree class


class BinarySearchTree:
def __init__(self):
self.root = None # Initially, the tree is empty

# Function to insert a new node in the BST


def insert(self, data):
if self.root is None:
self.root = Node(data) # If the tree is empty, create the root node
else:
self._insert(self.root, data) # Call the recursive insert function

# Recursive function to insert a new node in the correct position


def _insert(self, current_node, data):
# If the data is smaller, go to the left child
if data < current_node.data:
if current_node.left is None:
current_node.left = Node(data) # Insert as the left child
else:
self._insert(current_node.left, data) # Recur for left subtree
# If the data is larger, go to the right child
elif data > current_node.data:
if current_node.right is None:
current_node.right = Node(data) # Insert as the right child
else:
self._insert(current_node.right, data) # Recur for right subtree

# Function to display the tree in order (inorder traversal)


def inorder(self):
self._inorder(self.root) # Call the recursive inorder function
print() # To print a new line after the tree elements

# Recursive inorder function to display the tree


def _inorder(self, node):
if node:
self._inorder(node.left) # Traverse the left subtree
print(node.data, end=" ") # Print the node data
self._inorder(node.right) # Traverse the right subtree

# Example usage
bst = BinarySearchTree() # Create a new Binary Search Tree

# Insert elements into the BST


bst.insert(50)
bst.insert(30)
bst.insert(70)
bst.insert(20)
bst.insert(40)
bst.insert(60)
bst.insert(80)

# Display the tree using inorder traversal


print("Inorder Traversal of the Binary Search Tree:")
bst.inorder()

Output:

13. Write a python program for implementing graph with DFS traversal.
Input:

# Define the Graph class


class Graph:
def __init__(self):
self.graph = {} # A dictionary to store the graph (adjacency list)

# Function to add a vertex (node) to the graph


def add_vertex(self, vertex):
if vertex not in self.graph:
self.graph[vertex] = [] # Initialize an empty list for each vertex

# Function to add an edge between two vertices


def add_edge(self, vertex1, vertex2):
if vertex1 not in self.graph:
self.add_vertex(vertex1) # Add vertex1 if it's not already in the graph
if vertex2 not in self.graph:
self.add_vertex(vertex2) # Add vertex2 if it's not already in the graph
self.graph[vertex1].append(vertex2) # Add vertex2 to the adjacency list
of vertex1
self.graph[vertex2].append(vertex1) # Add vertex1 to the adjacency list
of vertex2 (undirected graph)

# Function for Depth-First Search (DFS) traversal


def dfs(self, start_vertex):
visited = set() # Set to keep track of visited vertices
self._dfs_recursive(start_vertex, visited) # Call the recursive DFS
helper function

# Recursive helper function for DFS


def _dfs_recursive(self, vertex, visited):
print(vertex, end=" ") # Print the current vertex
visited.add(vertex) # Mark the vertex as visited

for neighbor in self.graph[vertex]: # Traverse all adjacent vertices


if neighbor not in visited:
self._dfs_recursive(neighbor, visited) # Recur for unvisited
neighbor

# Example usage
g = Graph()

# Add vertices and edges


g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(2, 5)
g.add_edge(3, 6)

print("DFS Traversal starting from vertex 1:")


g.dfs(1)

Output:

14. Write a python program for implementing graph with BFS traversal.
Input:

from collections import deque

# BFS from given source s


def bfs(adj, s):

# Create a queue for BFS


q = deque()

# Initially mark all the vertices as not visited


# When we push a vertex into the q, we mark it as
# visited
visited = [False] * len(adj);

# Mark the source node as visited and enqueue it


visited[s] = True
q.append(s)

# Iterate over the queue


while q:

# Dequeue a vertex from queue and print it


curr = q.popleft()
print(curr, end=" ")

# Get all adjacent vertices of the dequeued


# vertex. If an adjacent has not been visited,
# mark it visited and enqueue it
for x in adj[curr]:
if not visited[x]:
visited[x] = True
q.append(x)

# Function to add an edge to the graph


def add_edge(adj, u, v):
adj[u].append(v)
adj[v].append(u)

# Example usage
if __name__ == "__main__":

# Number of vertices in the graph


V=5

# Adjacency list representation of the graph


adj = [[] for _ in range(V)]

# Add edges to the graph


add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 3)
add_edge(adj, 1, 4)
add_edge(adj, 2, 4)

# Perform BFS traversal starting from vertex 0


print("BFS starting from 0: ")
bfs(adj, 0)

Output:
15. Write a Python program for linear search.
Input:

# Function to perform linear search


def linear_search(arr, target):
# Iterate through each element in the array
for index in range(len(arr)):
if arr[index] == target: # Check if the element matches the target
return index # Return the index of the found element
return -1 # Return -1 if the target element is not found

# Example usage
arr = [10, 20, 30, 40, 50]
target = 30

# Perform linear search and print the result


result = linear_search(arr, target)

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

Output:

16. Write a python Program for Binary Search Using Recursive approach.
Input:

# Function to perform binary search recursively


def binary_search(arr, low, high, target):
# Base case: If the range is invalid (low > high)
if low > high:
return -1 # Target is not found

mid = (low + high) // 2 # Find the middle element

# If the target is at the middle


if arr[mid] == target:
return mid

# If the target is smaller than the middle element, search the left half
elif arr[mid] > target:
return binary_search(arr, low, mid - 1, target)

# If the target is larger than the middle element, search the right half
else:
return binary_search(arr, mid + 1, high, target)

# Example usage
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The array must be sorted
target = 60
# Call the binary search function
result = binary_search(arr, 0, len(arr) - 1, target)

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

Output:

17. Write a Python program for binary search using iterative approach.
Input:

# Function to perform binary search iteratively


def binary_search(arr, target):
low = 0 # Initial low index
high = len(arr) - 1 # Initial high index

# While loop to search for the target


while low <= high:
mid = (low + high) // 2 # Find the middle index

# If the target is at the middle


if arr[mid] == target:
return mid # Return the index of the target element

# If the target is smaller than the middle element, search the left half
elif arr[mid] > target:
high = mid - 1

# If the target is larger than the middle element, search the right half
else:
low = mid + 1

return -1 # Return -1 if the target is not found

# Example usage
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The array must be sorted
target = 50

# Perform binary search and print the result


result = binary_search(arr, target)

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

Output:
18. Write a python Program for bubble sort.
Input:

# Function to perform bubble sort


def bubble_sort(arr):
n = len(arr) # Length of the array
for i in range(n - 1):
# Traverse through the array from the start to the end of the unsorted
portion
for j in range(n - i - 1):
# Swap if the element is greater than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)

# Perform bubble sort


bubble_sort(arr)
print("Sorted array:", arr)
Output:

19. Write a python Program for implementation of merge sort.


Input:

# Function to merge two halves


def merge_sort(arr):
if len(arr) <= 1: # Base case: array is already sorted
return arr

# Split the array into two halves


mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])

# Merge the two sorted halves


return merge(left_half, right_half)

# Helper function to merge two sorted arrays


def merge(left, right):
result = [] # To store the merged result
i=j=0

# Compare elements from both arrays and append the smaller one
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
# Add any remaining elements from left or right
result.extend(left[i:])
result.extend(right[j:])
return result

# Example usage
arr = [5, 3, 8, 4, 2, 7, 1, 6]
print("Original array:", arr)

# Sort the array using merge sort


sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)

Output:

20. Write a python program for implementation of quick sort.


Input:

# Function to perform quick sort


def quick_sort(arr):
if len(arr) <= 1: # Base case: If array has 1 or no element, it's already
sorted
return arr

pivot = arr[0] # Choose the first element as the pivot


smaller = [x for x in arr[1:] if x <= pivot] # Elements smaller than or equal
to pivot
larger = [x for x in arr[1:] if x > pivot] # Elements greater than pivot

# Recursively sort smaller and larger arrays, then combine with pivot
return quick_sort(smaller) + [pivot] + quick_sort(larger)

# Example usage
arr = [3, 6, 8, 10, 1, 2, 1]
print("Original array:", arr)

# Sort the array using quick sort


sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)

Output:

You might also like