Fycs Daa Practical Manual
Fycs Daa Practical Manual
ALGORITHM PRACTICAL
MANUAL
FYCS SEM II
www.profajaypashankar.com
PROF.AJAY PASHANKAR
www.profajaypashankar.com
FYCS SEM II DESIGN AND ANALYSIS OF ALGORITHM PRACTICAL MANUAL BY : PROF.AJAY PASHANKAR
1)Programs on 1-d arrays like - sum of elements of array, searching an element inarray, finding
minimum and maximum element in array, count the number ofeven and odd numbers in array.
For all such programs, also find the timeComplexity, compare if there are multiple methods
# Maximum Function
def getMax(arr, n):
res = arr[0]
for i in range(1,n):
res = max(res, arr[i])
return res
# Driver Program
arr = [12, 1234, 45, 67, 1]
n = len(arr)
print ("Minimum element of array:", getMin(arr))
print ("Maximum element of array:", getMax(arr, n))
#program 1 D
# program to count number of even and odd elements in an array
# checking if a number is
# completely divisible by 2
if (arr[i] & 1 == 1):
odd_count += 1 #odd_count=odd_count+1
else:
even_count += 1 #even_count=even_count+1
# Function Call
CountingEvenOdd(arr, n)
for i in range(m):
sum = 0
for j in range(n):
sum = sum + matrix[j][i]
print('Sum of column',i,':',sum)
principal = 0
secondary = 0;
for i in range(0, n):
for j in range(0, n):
# Driver code
a = [[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ]]
printDiagonalSums(a, 4)
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
-------------------------------------------------------------------------------------------------------------------
#program 2d multiply two matrices using nested loops
# Program to multiply two matrices using nested loops
# iterating by row of A
for i in range(len(A)):
# iterating by column by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
#PROGRAM 3 : Program to create a list-based stack and perform various stack operations.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def pop(self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped
a_stack = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
a_stack.push(int(do[1]))
elif operation == 'pop':
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))
elif operation == 'quit':
break
if (array[j] == k):
return j
return -1
array = [1, 3, 5, 7, 9]
k=7
n = len(array)
result = LinearSearch(array, n, k)
if(result == -1):
else:
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))
total_iteration = 0
while(has_swapped):
has_swapped = False
for i in range(len(list1) - total_iteration - 1):
if list1[i] > list1[i+1]:
# Swap
list1[i], list1[i+1] = list1[i+1], list1[i]
has_swapped = True
total_iteration += 1
print("The number of iteraton: ",total_iteration)
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort funtion
print("The sorted list is: ", bubble_sort(list1))
if minValueIndex != i :
temp = itemsList[i]
itemsList[i] = itemsList[minValueIndex]
itemsList[minValueIndex] = temp
return itemsList
el = [21,6,9,33,3]
print(selectionSort(el))
value = list1[i]
class pair:
def __init__(self):
self.min = 0
self.max = 0
# If there is only one element then return it as min and max both
if n == 1:
minmax.max = arr[0]
minmax.min = arr[0]
return minmax
return minmax
# Driver Code
if __name__ == "__main__":
arr = [1000, 11, 445, 1, 330, 3000]
arr_size = 6
minmax = getMinMax(arr, arr_size)
print("Minimum element is", minmax.min)
print("Maximum element is", minmax.max)
Output:-
-------------------------------------------------------------------------------------------------------------------
7) Programs to find a pattern in a given string - general way and brute force
technique. Compare the efficiency of algorithms.
Program7A: Program to find a pattern by general way
#Program 7A program to find a pattern by general way
# Python3 program for Naive Pattern
# Searching algorithm
def search(pat, txt):
M = len(pat)
N = len(txt)
www.profajaypashankar.com K.M.AGRAWAL COLLEGE 9
FYCS SEM II DESIGN AND ANALYSIS OF ALGORITHM PRACTICAL MANUAL BY : PROF.AJAY PASHANKAR
if (j == M):
print("Pattern found at index ", i)
# Driver Code
if __name__ == '__main__':
txt = "AABAACAADAABAAABAA"
pat = "AABA"
search(pat, txt)
Output:-
-------------------------------------------------------------------------------------------------------------------
def find_maximum(lst):
max = None
for el in lst:
if max == None or el > max:
max = el
return max
test_scores = [88, 93, 75, 100, 80, 67, 71, 92, 90, 83]
print(find_maximum(test_scores)) # returns 100
Output-
--------------------------------------------------------------------------------------------------------------------
8) Programs on recursion like factorial, fibonacci, tower of hanoi. Compare
algorithms to find factorial/fibonacci using iterative and recursive approaches.
Program 8A: Program on recursion- factorial recursion
# Python 3 program to find
# factorial of given number
def factorial(n):
return 1
else:
# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))
Output-
nterms = 10
-------------------------------------------------------------------------------------------------------------------
program 8C: Program on recursion-Tower of Hanoi
#Program 8C program on recursion- Tower of Hanoi
# Recursive Python function to solve the tower of hanoi
# Driver code
n=4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
Output-
class Heap():
# Building own implementation of Min Heap
def __init__(self):
self.h = []
if index > 0:
return (index - 1) // 2
return (2 * index) + 1
return (2 * index) + 2
if len(self.h) == 1:
index = len(self.h) - 1
parent = self.parent(index)
def deleteItem(self):
return deleted
if smallest != index:
# Swaps the parent node with the smaller child
self.h[smallest], self.h[index] = self.h[index], self.h[smallest]
self.h[index] = value
self.moveDownHeapify(index)
class OptimalMergePattern():
def __init__(self, n, items):
self.n = n
self.items = items
self.heap = Heap()
def optimalMerge(self):
if self.n == 1:
return self.items[0]
count = 0
while len(self.heap.h) != 1:
tmp = self.heap.deleteItem()
count += (tmp + self.heap.h[0])
self.heap.increaseItem(0, tmp + self.heap.h[0])
return count
# Driver Code
if __name__ == '__main__':
OMP = OptimalMergePattern(6, [2, 3, 4, 5, 6, 7])
ans = OMP.optimalMerge()
print(ans)
Output-
www.profajaypashankar.com K.M.AGRAWAL COLLEGE 15
FYCS SEM II DESIGN AND ANALYSIS OF ALGORITHM PRACTICAL MANUAL BY : PROF.AJAY PASHANKAR
----------------------------------------------------------------------------------------------------------------------
Program 9B: Program to implement coin change problems using greedy algorithm
# Python3 program to find minimum
# number of denominations
def findMin(V):
# Initialize Result
ans = []
# Find denominations
while (V >= deno[i]):
V -= deno[i]
ans.append(deno[i])
i -= 1
# Print result
for i in range(len(ans)):
print(ans[i], end = " ")
# Driver Code
if __name__ == '__main__':
n = 93
print("Following is minimal number",
"of change for", n, ": ", end = "")
findMin(n)
#
# Surendra_Gangwar
Output-
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")
# Mohit Kumra
Output-
----------------------------------------------------------------------------------------------------------------------
Program 10B:Program to implement Strassen’’s matrix multiplication using D-n-C algorithm
import numpy as np
n = x.shape[0]
if n % 2 == 1:
x = np.pad(x, (0, 1), mode='constant')
y = np.pad(y, (0, 1), mode='constant')
m = int(np.ceil(n / 2))
a = x[: m, : m]
b = x[: m, m:]
c = x[m:, : m]
d = x[m:, m:]
e = y[: m, : m]
f = y[: m, m:]
g = y[m:, : m]
h = y[m:, m:]
p1 = strassen_algorithm(a, f - h)
p2 = strassen_algorithm(a + b, h)
p3 = strassen_algorithm(c + d, e)
p4 = strassen_algorithm(d, g - e)
p5 = strassen_algorithm(a + d, e + h)
p6 = strassen_algorithm(b - d, g + h)
p7 = strassen_algorithm(a - c, e + f)
result = np.zeros((2 * m, 2 * m), dtype=np.int32)
result[: m, : m] = p5 + p4 - p2 + p6
return result[: n, : n]
if __name__ == "__main__":
----------------------------------------------------------------------------------------------------------------
Program11B: Program to implement longest common subsequence using dynamic
programming
# Dynamic Programming implementation of LCS problem
Output-
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
return True
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# Divyanshu Mehta
Output-
----------------------------------------------------------------------------------------------------------------
Program 12B: Program to implement Binary String generation using
Backtracking Strategy
# Python3 implementation of the
# above approach
print()
if i == n:
printTheArray(arr, n)
return
# Driver Code
if __name__ == "__main__":
n=4
arr = [None] * n