Ada Sumission Adib

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Practical-1

Aim: Implementation and Time analysis of sorting algorithms.


Bubble sort, Selection sort, Insertion sort, Merge sort and Quicksort

BubbleSort:

def bubbleSort(arr):
n = len(arr)
# optimize code, so if the array is already sorted, it doesn't need
# to go through the entire process
swapped = False
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will
# repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]

if not swapped:
# if we haven't needed to make a single swap, we
# can just exit the main loop.
return

Adib Lokhandwala TY_CE_2A 210410107063


# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print("Sorted array is:")


for i in range(len(arr)):
print("% d" % arr[i], end=" ")

Output:

Adib Lokhandwala TY_CE_2A 210410107063


InsertionSort:

def insertion_sort(list1):

# Outer loop to traverse through 1 to len(list1)


for i in range(1, len(list1)):

value = list1[i]

# Move elements of list1[0..i-1], that are


# greater than value, to one position ahead
# of their current position
j=i-1
while j >= 0 and value < list1[j]:
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
# Driver code to test above

list1 = [10, 5, 13, 8, 2]


print("The unsorted list is:", list1)

print("The sorted list1 is:", insertion_sort(list1))

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Quicksort:

def partition(array, low, high):

pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1

def quickSort(array, low, high):


if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)

data = [1, 7, 4, 1, 10, 9, -2]


print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


MergeSort:
def merge_sort(list1, left_index, right_index):
if left_index >= right_index: # here, we are checking the if condition
return
middle = (left_index + right_index)//2
merge_sort(list1, left_index, middle)
merge_sort(list1, middle + 1, right_index)
merge(list1, left_index, right_index, middle)

def merge(list1, left_index, right_index, middle):


left_sublist = list1[left_index:middle + 1]
right_sublist = list1[middle+1:right_index+1]
left_sublist_index = 0
right_sublist_index = 0
sorted_index = left_index
while left_sublist_index < len(left_sublist) and right_sublist_index <
len(right_sublist):
if left_sublist[left_sublist_index] <= right_sublist[right_sublist_index]:
list1[sorted_index] = left_sublist[left_sublist_index]
left_sublist_index = left_sublist_index + 1
else:
list1[sorted_index] = right_sublist[right_sublist_index]
right_sublist_index = right_sublist_index + 1
sorted_index = sorted_index + 1
while left_sublist_index < len(left_sublist): # here, we are declaring a while loop
list1[sorted_index] = left_sublist[left_sublist_index]
left_sublist_index = left_sublist_index + 1
sorted_index = sorted_index + 1
sorted_index = sorted_index + 1

Adib Lokhandwala TY_CE_2A 210410107063


list1 = [44, 65, 2, 3, 58, 14, 57, 23, 10, 1, 7, 74, 48]
print("The given list before performing the merge sort is: ", list1)
merge_sort(list1, 0, len(list1) -1)
print("The given list after performing the merge sort is:", list1)

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-2
Aim: Implementation and Time analysis of linear and binary search algorithm.

LinearSearch:

import random
import time
random.seed(42)
def linearSearch(array, n, x):

for i in range(0, n):


if (array[i] == x):
return i
return -1

arr = random.sample(range(1,100000000), 10000000)


arr.sort()

start = time.time()
index = linearSearch(arr, len(arr),27978215)
print(f"found element at {index}")
end = time.time()
print("took", end-start, "milliseconds")

Output:

Adib Lokhandwala TY_CE_2A 210410107063


BinarySearch:

def binarySearch(array, x, low, high):

while low <= high:

mid = low + (high - low)//2

if array[mid] == x:
return mid

elif array[mid] < x:


low = mid + 1

else:
high = mid - 1

return -1

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-3
Aim: Implementation of max-heap sort algorithm

Code:
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2

if l < n and arr[i] < arr[l]:


largest = l

if r < n and arr[largest] < arr[r]:


largest = r

if largest != i:
(arr[i], arr[largest]) = (arr[largest], arr[i]) # swap
heapify(arr, n, largest)

def heapSort(arr):
n = len(arr)

for i in range(n // 2 - 1, -1, -1):


heapify(arr, n, i)

for i in range(n - 1, 0, -1):

Adib Lokhandwala TY_CE_2A 210410107063


(arr[i], arr[0]) = (arr[0], arr[i]) # swap
heapify(arr, i, 0)

arr = [12, 11, 13, 5, 6, 7, ]


print("before sorting", arr)
heapSort(arr)
print("after sorting: ",arr)

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-4
Aim: Implementation and time analysis of factorial program using
iterative and recursive method

Iterative method:

def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact

num = 5
print("Factorial of",num,"is",
factorial(num))

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Recursive Method:

def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1)

num = 5
print ("Factorial of",num,"is",
factorial(num)

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-5
Aim: Implementation of Knapsack problem using Dynamic Programming

Code:

def knapSack(W, wt, val, n):


#base case
if n == 0 or W == 0:
return 0

if (wt[n-1] > W):


return knapSack(W, wt, val, n-1)

else:
return max(
val[n-1] + knapSack(
W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))

if __name__ == '__main__':
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50
n = len(profit)
print(knapSack(W, weight, profit, n))

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-6
Aim: Implementation of Chain Matrix Multiplication using Dynamic
Programming

Code:
import sys
def MatrixChainOrder(p, i, j):
if i == j:
return 0

_min = sys.maxsize

for k in range(i, j):

count = (MatrixChainOrder(p, i, k)
+ MatrixChainOrder(p, k + 1, j)
+ p[i-1] * p[k] * p[j])

if count < _min:


_min = count
return _min

if __name__ == '__main__':
arr = [1, 2, 3, 4, 3]
N = len(arr)

print("Minimum number of multiplications is ",


MatrixChainOrder(arr, 1, N-1))

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-7
Aim: Implementation of Making Change Problem using Dynamic
Programming

Code:

def getNumberOfWays(N, Coins):

ways = [0] * (N + 1);

ways[0] = 1;

for i in range(len(Coins)):
if (Coins[i] <= j):
ways[j] += ways[(int)(j - Coins[i])];

return ways[N];

def printArray(coins):
for i in coins:
print(i);

if __name__ == '__main__':
Coins = [1, 5, 10];

print("The Coins Array:");


printArray(Coins);

print("Solution:",end="");
print(getNumberOfWays(12, Coins));

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-8
Aim: Implementation of Knapsack problem using greedy algorithm

Code:

class Item:
def __init__(self, profit, weight):
self.profit = profit
self.weight = weight

def fractionalKnapsack(W, arr):

arr.sort(key=lambda x: (x.profit/x.weight), reverse=True)


finalvalue = 0.0

for item in arr:

if item.weight <= W:
W -= item.weight
finalvalue += item.profit
else:
finalvalue += item.profit * W / item.weight
break
return finalvalue

if __name__ == "__main__":
W = 50
arr = [Item(60, 10), Item(100, 20), Item(120, 30)]
max_val = fractionalKnapsack(W, arr)
print(max_val)

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-9
Aim: Implementation of Graph and Searching (DFS and BFS)

DFS:
from collections import defaultdict as dd

class Graph:
def __init__(self):
self.graph = dd(list)

def addEdgetoGraph(self, x, y):


self.graph[x].append(y)

def BFSearch(self, n):


visited_vertices = ( len(self.graph ))*[False]

queue = []
visited_vertices[n] = True
queue.append(n)

while queue:
n = queue.pop(0)
print (n, end = " ")

for v in self.graph[ n ]:
if visited_vertices[v] == False:
queue.append(v)
visited_vertices[v] = True

Adib Lokhandwala TY_CE_2A 210410107063


graph = Graph()
graph.addEdgetoGraph(0, 1)
graph.addEdgetoGraph(1, 1)
graph.addEdgetoGraph(2, 2)
graph.addEdgetoGraph(3, 1)
graph.addEdgetoGraph(4, 3)
graph.addEdgetoGraph(5, 4)

print ( " The Breadth First Search Traversal for The Graph is as Follows: " )
graph.BFSearch(3)

Output:

Adib Lokhandwala TY_CE_2A 210410107063


DFS:
def dfs(node, graph, visited, component):
component.append(node) # Store answer
visited[node] = True # Mark visited

# Traverse to each adjacent node of a node


for child in graph[node]:
if not visited[child]: # Check whether the node is visited or not
dfs(child, graph, visited, component) # Call the dfs recursively

if __name__ == "__main__":

# Graph of nodes
graph = {
0: [2],
1: [2, 3],
2: [0, 1, 4],
3: [1, 4],
4: [2, 3]
}
node = 0 # Starting node
visited = [False]*len(graph) # Make all nodes to False initially
component = []
dfs(node, graph, visited, component) # Traverse to each node of a graph
print(f"Following is the Depth-first search: {component}") # Print the answer

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-10
Aim: Implementation of Prim’s Algorithm

Code:
import sys

class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printMST(self, parent):


print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])

def minKey(self, key, mstSet):


min = sys.maxsize

for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v

return min_index

def primMST(self):

key = [sys.maxsize] * self.V

Adib Lokhandwala TY_CE_2A 210410107063


parent = [None] * self.V # Array to store constructed MST
key[0] = 0
mstSet = [False] * self.V

parent[0] = -1 # First node is always the root of

for cout in range(self.V):


u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False \
and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u

self.printMST(parent)

if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]

g.primMST()

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-11
Aim: Implementation of Kruskal’s Algorithm

Code:
class Graph:

def __init__(self, vertices):


self.V = vertices
self.graph = []

def addEdge(self, u, v, w):


self.graph.append([u, v, w])

def find(self, parent, i):


if parent[i] != i:
parent[i] = self.find(parent, parent[i])
return parent[i]

def union(self, parent, rank, x, y):

if rank[x] < rank[y]:


parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x

else:
parent[y] = x
rank[x] += 1

def KruskalMST(self):

Adib Lokhandwala TY_CE_2A 210410107063


result = []

i=0

e=0

self.graph = sorted(self.graph,
key=lambda item: item[2])

parent = []
rank = []

for node in range(self.V):


parent.append(node)
rank.append(0)

while e < self.V - 1:

u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)

if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)

Adib Lokhandwala TY_CE_2A 210410107063


minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)

if __name__ == '__main__':
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)

# Function call
g.KruskalMST()

Output:

Adib Lokhandwala TY_CE_2A 210410107063


Practical-12
Aim: Implementation of LCS (Longest Common Subsequence) problem

Code:

def lcs(X, Y, m, n):

if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

X = "AGGTAB"
Y = "GXTXAYB"
print ("Length of LCS is ", lcs(X, Y, len(X), len(Y)))

Output:

Adib Lokhandwala TY_CE_2A 210410107063


OEP
Aim: From the given string find maximum size possible palindrome sequence

Code:

def max(x, y):


if(x > y):
return x
return y

def lps(seq, i, j):


if (i == j):
return 1

if (seq[i] == seq[j] and i + 1 == j):


return 2

if (seq[i] == seq[j]):
return lps(seq, i + 1, j - 1) + 2

return max(lps(seq, i, j - 1),


lps(seq, i + 1, j))

if __name__ == '__main__':
seq = "GEEKSFORGEEKS"
n = len(seq)
print("The length of the LPS is",
lps(seq, 0, n - 1))

Adib Lokhandwala TY_CE_2A 210410107063


Output:

Adib Lokhandwala TY_CE_2A 210410107063

You might also like