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

sdfinall

Uploaded by

msd130105
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

sdfinall

Uploaded by

msd130105
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 1 Write a program to perform using NumPy to perform Various functions in Array.

Program :

import numpy as np

# Creating an array

arr = np.array([10, 20, 30, 40, 50])

# Various operations

print("Original Array:", arr)

print("Sum of array:", np.sum(arr))

print("Mean of array:", np.mean(arr))

print("Max value:", np.max(arr))

print("Min value:", np.min(arr))

print("Sorted Array:", np.sort(arr))

print("Square of each element:", np.square(arr))

Output :

1
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 2 Write a program to implement a Sparse Matrix.

Program :

import numpy as np

def sparse_matrix(matrix):

sparse = []

for i in range(len(matrix)):

for j in range(len(matrix[0])):

if matrix[i][j] != 0:

sparse.append((i, j, matrix[i][j]))

return sparse

# Input Matrix

matrix = [

[5, 0, 0],

[0, 8, 0],

[0, 0, 3]

print("Original Matrix:")

for row in matrix:

print(row)

print("Sparse Matrix Representation:")

2
print(sparse_matrix(matrix))

Output :

3
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 3 Write a program to perform String Manipulations using Array.

Program :

from array import array

def string_manipulations(s):

arr = array('u', s) # Unicode array

print("Original String Array:", "".join(arr))

# Reversing the string

arr.reverse()

print("Reversed String:", "".join(arr))

# Adding a character

arr.append('!')

print("After Adding a Character:", "".join(arr))

# Removing a character

arr.pop()

print("After Removing Last Character:", "".join(arr))

string_manipulations("hello")

4
Output :

5
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 10 Write a program to perform the following operations:

a) Insert an element into a binary search tree.

b) Delete an element from a binary search tree.

c) Search for a key element in a binary search tree

Program :

class Node:

def init (self, key):

self.left = None

self.right = None

self.key = key

# Insert function

def insert(root, key):

if root is None:

return Node(key)

elif key < root.key:

root.left = insert(root.left, key)

else:

root.right = insert(root.right, key)

return root

# Delete function

def delete(root, key):


30
if root is None:

return root

if key < root.key:

root.left = delete(root.left, key)

elif key > root.key:

root.right = delete(root.right, key)

else:

# Node with one or no child

if root.left is None:

return root.right

elif root.right is None:

return root.left

# Node with two children: get the inorder successor

temp = find_min(root.right)

root.key = temp.key

root.right = delete(root.right, temp.key)

return root

# Find the minimum value (used in deletion)

def find_min(node):

current = node

while current.left is not None:

current = current.left

return current

# Search function

def search(root, key):

if root is None or root.key == key:

return root
31
if key < root.key:

return search(root.left, key)

return search(root.right, key)

# Inorder Traversal (to display BST elements)

def inorder(root):

if root:

inorder(root.left)

print(root.key, end=" ")

inorder(root.right)

# Menu-Driven Program

root = None

while True:

print("\n1. Insert 2. Delete 3. Search 4. Display (Inorder) 5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter key to insert: "))

root = insert(root, key)

elif choice == 2:

key = int(input("Enter key to delete: "))

root = delete(root, key)

elif choice == 3:

key = int(input("Enter key to search: "))

result = search(root, key)

if result:

print(f"Key {key} found in the BST")

else:

print(f"Key {key} not found in the BST")


32
elif choice == 4:

print("BST Elements (Inorder Traversal): ", end="")

inorder(root)

print()

elif choice == 5:

break

Output :

33
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 11 Write a program to search an element by using Linear search method

Program :

def linear_search(arr, x):

for i in range(len(arr)):

if arr[i] == x:

return i # Return index if found

return -1 # Return -1 if not found

# Input and Testing

arr = list(map(int, input("Enter array elements: ").split()))

x = int(input("Enter element to search: "))

result = linear_search(arr, x)

if result != -1:

print(f"Element found at index {result}")

else:

print("Element not found")

Output :

34
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 12 Write a program to search an element by using Binary search method

Program :

def binary_search(arr, x):

low, high = 0, len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == x:

return mid

elif arr[mid] < x:

low = mid + 1

else:

high = mid - 1

return -1

# Input and Testing

arr = sorted(list(map(int, input("Enter sorted array elements: ").split())))

x = int(input("Enter element to search: "))

result = binary_search(arr, x)

if result != -1:

print(f"Element found at index {result}")

else:

35
print("Element not found")

Output :

36
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 13 Write a program to implement the tree traversal methods.

Program :

class Node:

def init (self, key):

self.left = None

self.right = None

self.key = key

# Traversal Functions

def preorder(root):

if root:

print(root.key, end=" ")

preorder(root.left)

preorder(root.right)

def inorder(root):

if root:

inorder(root.left)

print(root.key, end=" ")

inorder(root.right)

def postorder(root):

if root:

postorder(root.left)
37
postorder(root.right)

print(root.key, end=" ")

# Insert into Binary Tree

def insert(root, key):

if root is None:

return Node(key)

elif key < root.key:

root.left = insert(root.left, key)

else:

root.right = insert(root.right, key)

return root

# Menu-Driven Program

root = None

while True:

print("\n1. Insert 2. Preorder 3. Inorder 4. Postorder 5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter key to insert: "))

root = insert(root, key)

elif choice == 2:

print("Preorder Traversal: ", end="")

preorder(root)

print()

elif choice == 3:

print("Inorder Traversal: ", end="")

inorder(root)

print()
38
elif choice == 4:

print("Postorder Traversal: ", end="")

postorder(root)

print()

elif choice == 5:

break

Output :

39
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 14 Write a program to perform the following operations:

Insert an element into a AVL tree.

Delete an element from a AVL tree.

Search for a key element in a AVL tree.

Program :

class Node:

def init (self, key):

self.key = key

self.left = None

self.right = None

self.height = 1

def get_height(node):

if not node:

return 0

return node.height

def get_balance(node):

if not node:

return 0

return get_height(node.left) - get_height(node.right)

def rotate_right(y):

40
x = y.left

T2 = x.right

x.right = y

y.left = T2

y.height = 1 + max(get_height(y.left), get_height(y.right))

x.height = 1 + max(get_height(x.left), get_height(x.right))

return x

def rotate_left(x):

y = x.right

T2 = y.left

y.left = x

x.right = T2

x.height = 1 + max(get_height(x.left), get_height(x.right))

y.height = 1 + max(get_height(y.left), get_height(y.right))

return y

# Insert operation

def insert(node, key):

if not node:

return Node(key)

if key < node.key:

node.left = insert(node.left, key)

else:

node.right = insert(node.right, key)

node.height = 1 + max(get_height(node.left), get_height(node.right))

balance = get_balance(node)

# Left heavy
41
if balance > 1 and key < node.left.key:

return rotate_right(node)

# Right heavy

if balance < -1 and key > node.right.key:

return rotate_left(node)

# Left-Right heavy

if balance > 1 and key > node.left.key:

node.left = rotate_left(node.left)

return rotate_right(node)

# Right-Left heavy

if balance < -1 and key < node.right.key:

node.right = rotate_right(node.right)

return rotate_left(node)

return node

# Inorder Traversal

def inorder(node):

if node:

inorder(node.left)

print(node.key, end=" ")

inorder(node.right)

# Search operation

def search(node, key):

if not node or node.key == key:

return node

if key < node.key:

return search(node.left, key)


42
return search(node.right, key)

# Menu-driven Program

root = None

while True:

print("\n1. Insert 2. Search 3. Display Inorder 4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter key to insert: "))

root = insert(root, key)

elif choice == 2:

key = int(input("Enter key to search: "))

result = search(root, key)

print(f"Key {key} found" if result else f"Key {key} not found")

elif choice == 3:

print("Inorder Traversal of AVL Tree: ", end="")

inorder(root)

print()

elif choice == 4:

break

43
Output :

44
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 15 Write a program to implement the Graph methods.

 Adjacency Matrix

 Adjacency List

Program :

# Graph using Adjacency Matrix

def adjacency_matrix(vertices, edges):

matrix = [[0] * vertices for _ in range(vertices)]

for edge in edges:

u, v = edge

matrix[u][v] = 1

matrix[v][u] = 1 # For undirected graph

return matrix

# Graph using Adjacency List

def adjacency_list(vertices, edges):

adj_list = {i: [] for i in range(vertices)}

for edge in edges:

u, v = edge

adj_list[u].append(v)

adj_list[v].append(u) # For undirected graph

return adj_list

45
# Input

vertices = int(input("Enter number of vertices: "))

edges_count = int(input("Enter number of edges: "))

edges = []

for _ in range(edges_count):

u, v = map(int, input("Enter edge (u, v): ").split())

edges.append((u, v))

# Output

print("\nAdjacency Matrix:")

matrix = adjacency_matrix(vertices, edges)

for row in matrix:

print(row)

print("\nAdjacency List:")

adj_list = adjacency_list(vertices, edges)

for key, value in adj_list.items():

print(f"{key}: {value}")

Output :

46
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 16 Write a program to implement the Graph traversal methods

 BFS

 DFS

Program :

from collections import deque

def bfs(graph, start):

visited = set()

queue = deque([start])

print("BFS Traversal: ", end="")

while queue:

node = queue.popleft()

if node not in visited:

print(node, end=" ")

visited.add(node)

for neighbor in graph[node]:

if neighbor not in visited:

queue.append(neighbor)

def dfs(graph, start, visited=None):

if visited is None:

visited = set()

visited.add(start)
47
print(start, end=" ")

for neighbor in graph[start]:

if neighbor not in visited:

dfs(graph, neighbor, visited)

# Input

vertices = int(input("Enter number of vertices: "))

edges_count = int(input("Enter number of edges: "))

graph = {i: [] for i in range(vertices)}

for _ in range(edges_count):

u, v = map(int, input("Enter edge (u, v): ").split())

graph[u].append(v)

graph[v].append(u)

# Traversal

start = int(input("Enter starting vertex: "))

bfs(graph, start)

print("\nDFS Traversal: ", end="")

dfs(graph, start)

48
Output :

49
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 17 Write a program to sort an elements by using Bubble sort method .

Program :

def bubble_sort(arr):

n = len(arr)

for i in range(n):

for j in range(n - i - 1):

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Input and Testing

arr = list(map(int, input("Enter elements to sort: ").split()))

bubble_sort(arr)

print("Sorted Array:", arr)

Output :

50
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 18 Write a program to sort an elements by using Merge sort method .

Program :

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

51
arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

# Input and Testing

arr = list(map(int, input("Enter elements to sort: ").split()))

merge_sort(arr)

print("Sorted Array:", arr)

Output :

52
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 19 Write a program to sort an elements by using Quick sort method.

Program :

def partition(arr, low, high):

pivot = arr[high] # Choose the last element as the pivot

i = low - 1 # Index of smaller element

for j in range(low, high):

if arr[j] < pivot:

i += 1

arr[i], arr[j] = arr[j], arr[i] # Swap

arr[i + 1], arr[high] = arr[high], arr[i + 1]

return i + 1

def quick_sort(arr, low, high):

if low < high:

pi = partition(arr, low, high) # Partitioning index

quick_sort(arr, low, pi - 1) # Sort elements before partition

quick_sort(arr, pi + 1, high) # Sort elements after partition

# Input and Testing

arr = list(map(int, input("Enter elements to sort: ").split()))

quick_sort(arr, 0, len(arr) - 1)

print("Sorted Array:", arr)

53
Output :

54
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 20 Write a program that implements the following methods

Heap sort.

Program :

def heapify(arr, n, i):

largest = i # Initialize the largest as root

left = 2 * i + 1

right = 2 * i + 2

if left < n and arr[left] > arr[largest]:

largest = left

if right < n and arr[right] > arr[largest]:

largest = right

if largest != i:

arr[i], arr[largest] = arr[largest], arr[i]

heapify(arr, n, largest)

def heap_sort(arr):

n = len(arr)

for i in range(n // 2 - 1, -1, -1): # Build a max heap

heapify(arr, n, i)

55
for i in range(n - 1, 0, -1): # Extract elements

arr[i], arr[0] = arr[0], arr[i]

heapify(arr, i, 0)

# Input and Testing

arr = list(map(int, input("Enter elements to sort: ").split()))

heap_sort(arr)

print("Sorted Array:", arr)

Output :

56
SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION


DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105

STUDENT NAME:

CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….

DATE OF SUBMISSION :-………………………………………………………………………….

TITLE :- 21 Write a program that implements the Hash Methods

Program :

class HashTable:

def init (self, size):

self.size = size

self.table = [None] * size

def hash_function(self, key):

return key % self.size

def insert(self, key):

index = self.hash_function(key)

if self.table[index] is None:

self.table[index] = key

else:

print(f"Collision occurred for key {key} at index {index}")

def search(self, key):

index = self.hash_function(key)

if self.table[index] == key:

print(f"Key {key} found at index {index}")

else:

print(f"Key {key} not found")

57
def display(self):

print("Hash Table:")

for i, value in enumerate(self.table):

print(f"Index {i}: {value}")

# Menu-driven program

size = int(input("Enter size of hash table: "))

hash_table = HashTable(size)

while True:

print("\n1. Insert 2. Search 3. Display 4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter key to insert: "))

hash_table.insert(key)

elif choice == 2:

key = int(input("Enter key to search: "))

hash_table.search(key)

elif choice == 3:

hash_table.display()

elif choice == 4:

break

58
Output :

59

You might also like