Python DSA Programs
Python DSA Programs
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
Pune-28. She has successfully completed the practical work in the subject
Python Programming and Data structure and Algorithms (IT-11L) as per the
2024-25.
Date: / /2024
Place: Pune
INDEX
Python Programs
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
Output:
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 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}")
# Display details
bank.display_details()
Output:
# 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.")
import threading
# 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()
Output:
5. Write a program to overload “==” operator.
Input:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Example usage
person1 = Person("Anu", 30)
person2 = Person("Anu", 30)
person3 = Person("Sanu", 25)
Output:
class MyClass:
# Constructor with default argument
def __init__(self, name="Default"):
self.name = name
Output:
7. Write a program to create an employees collection in a mongodb
database and perform CRUD operations on this collection.
Input:
# 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
# Read
read_employee()
# Update
update_employee()
# Delete
delete_employee()
Output:
try:
# Accept input from the user
user_input = input("Enter an integer: ")
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:
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)
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!")
def greet(self):
super().greet() # Call the greet method of the first parent in the
MRO
print("Hello from Child!")
Input:
import threading
class BankAccount:
self.balance = balance
self.balance += amount
self.balance -= amount
account = BankAccount(1000)
# Function to simulate commit thread
def commit_thread():
account.commit(200)
def rollback_thread():
account.rollback(100)
thread1 = threading.Thread(target=commit_thread)
thread2 = threading.Thread(target=rollback_thread)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Output:
Output:
import re
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
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)
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)
Output:
# Create a 1D array
arr = array.array('i', [10, 20, 30, 40, 50]) # 'i' for integers
print("Original Array:", 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:
# Example usage
my_array = [10, 20, 30, 40, 50]
print("Array:", my_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
Output:
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)
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:
# Example usage
linked_list = LinkedList() # Create a new linked list
linked_list.append(10) # Add nodes
linked_list.append(20)
linked_list.append(30)
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
# Example usage
linked_list = LinkedList()
linked_list.append(10)
linked_list.append(20)
linked_list.append(30)
Output:
8. Write a Python program for doubly linked list to insert node at last position of
linked list.
Input:
# Example usage
dll = DoublyLinkedList() # Create an empty doubly 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
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
# 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()
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:
# Example usage
sll = SinglyLinkedList() # Create an empty singly linked list
# Insert nodes
sll.append(10)
sll.append(20)
sll.append(30)
sll.append(40)
Output:
11. Write a Python program for doubly linked list to sort the linked list in ascending
order.
Input:
# 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()
Output:
12. Write a Python program for binary search tree creation and insertion of elements.
Input:
# Example usage
bst = BinarySearchTree() # Create a new Binary Search Tree
Output:
13. Write a python program for implementing graph with DFS traversal.
Input:
# Example usage
g = Graph()
Output:
14. Write a python program for implementing graph with BFS traversal.
Input:
# Example usage
if __name__ == "__main__":
Output:
15. Write a Python program for linear search.
Input:
# Example usage
arr = [10, 20, 30, 40, 50]
target = 30
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:
# 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:
# 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
# Example usage
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The array must be sorted
target = 50
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:
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)
# 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)
Output:
# 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)
Output: