DAA LAB modified
DAA LAB modified
OUTPUT :
89
Time complexity : O(N)
Space complexity : O(1)
RECURSIVE ALGORITHM :
AIM : To find the factorial of a given number.
ALGORITHM:
1. Get an integer x as input.
2. Define a function F(x) to return factorial of a
number.
3. If the input is 0 then return 1 else return F(x-1)*x.
PROGRAM:
def factorial(x):
if x == 0:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
OUTPUT :
The factorial of 3 is 6.
Time complexity : O(N)
Space complexity : O(N)
C11 = m1 + m4 – m5 + m6
C12 = m3 + m5
C21 = m2 + m4
C22 = m1 + m4 – m2 + m6
PROGRAM :
import numpy as np
def split(matrix):
row, col = matrix.shape
row2, col2 = row//2, col//2
return matrix[:row2, :col2], matrix[:row2, col2:],
matrix[row2:, :col2], matrix[row2:, col2:]
def strassen(x, y):
if len(x) == 1:
return x * y
a, b, c, d = split(x)
e, f, g, h = split(y)
p1 = strassen(a, f - h)
p2 = strassen(a + b, h)
p3 = strassen(c + d, e)
p4 = strassen(d, g - e)
p5 = strassen(a + d, e + h)
p6 = strassen(b - d, g + h)
p7 = strassen(a - c, e + f)
c11 = p5 + p4 - p2 + p6
c12 = p1 + p2
c21 = p3 + p4
c22 = p1 + p5 - p3 - p7
c = np.vstack((np.hstack((c11, c12)),
np.hstack((c21, c22))))
return c
OUTPUT :
Time complexity : T(n) = 7 T(n/2) + O(n2)
self.topologicalSortUtil(i,visited,stack)
stack.insert(0,v)
def topologicalSort(self):
visited = [False]*self.V
stack =[]
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
print (stack)
g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print ("Following is a Topological Sort of the given
graph")
g.topologicalSort()
OUTPUT :
Following is a Topological Sort of the given graph
[5, 4, 2, 3, 1, 0]
Time complexity :O(|V| + |E| )
where V – vertices & E – edges
PROGRAM :
def heapify(arr, n, i):
largest = i
l=2*i+1
r=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])
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):
(arr[i], arr[0]) = (arr[0], arr[i])
heapify(arr, i, 0)
arr = [12, 11, 13, 5, 6, 7, ]
heapSort(arr)
n = len(arr)
print('Sorted array is')
for i in range(n):
print(arr[i])
OUTPUT :
Sorted array is
5
6
7
11
12
13
Time Complexity: O(n*log(n))
PROGRAM :
def count(S, m, n):
table = [[0 for x in range(m)] for x in range(n+1)]
for i in range(m):
table[0][i] = 1
for i in range(1, n+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0
table[i][j] = x + y
return table[n][m-1]
arr = [1, 3, 2, 4]
m = len(arr)
n=5
print(“Number of coins:”,end=””)
print(count(arr, m, n))
OUTPUT :
Number of coins:6
Time complexity : O(nxm)
where n - no. of subproblem & m - weight