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

DAA (all python prgms)(new)

The document contains multiple Python programs implementing various algorithms including linear search, binary search, Towers of Hanoi, selection sort, quick sort, binomial coefficient calculation, Floyd's algorithm, polynomial evaluation, and string matching using Boyer-Moore and KMP algorithms. Each program includes code snippets, explanations of the algorithms, and instructions to plot performance graphs or display outputs. The document serves as a comprehensive guide for implementing and experimenting with these algorithms in Python.

Uploaded by

faseeha221
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

DAA (all python prgms)(new)

The document contains multiple Python programs implementing various algorithms including linear search, binary search, Towers of Hanoi, selection sort, quick sort, binomial coefficient calculation, Floyd's algorithm, polynomial evaluation, and string matching using Boyer-Moore and KMP algorithms. Each program includes code snippets, explanations of the algorithms, and instructions to plot performance graphs or display outputs. The document serves as a comprehensive guide for implementing and experimenting with these algorithms in Python.

Uploaded by

faseeha221
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

DAA PROGRAMS IN PYTHON

1) Write a program to implement linear search algorithm.


Repeat the experiment for different values of n, the number
of elements in the list to be searched and plot a graph of time
taken versus n.

import time
import random
import matplotlib.pyplot as plt

def linear_search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1
n_values=[10, 100, 1000, 10000, 100000]
times = []
for n in n_values:
arr=['random.randint(e, n) for_in range(n)']
print("The Value of n = ",n)
print("The Array values:: ",arr)
x = random.randint(0, n)
print("The value of x = ",x)
start_time = time.time()
print("Start Time", start_time)
linear_search(arr, x)
end_time = time.time()
print("End time = ", end_time)
times.append(end_time-start_time)

plt.plot(n_values, times)
plt.xlabel('n')
plt.ylabel('Time taken (seconds)')
plt.show()

output: The Value of n = 10


The Array values:: ['random.randint(e, n) for_in range(n)']
The value of x = 6
Start Time 1714035645.10912
End time = 1714035645.1091597
The Value of n = 100
The Array values:: ['random.randint(e, n) for_in range(n)']
The value of x = 47
Start Time 1714035645.1092699
End time = 1714035645.109298
The Value of n = 1000
The Array values:: ['random.randint(e, n) for_in range(n)']
The value of x = 971
Start Time 1714035645.109414
End time = 1714035645.1094432
The Value of n = 10000
The Array values:: ['random.randint(e, n) for_in range(n)']
The value of x = 6431
Start Time 1714035645.1095562
End time = 1714035645.109589
The Value of n = 100000
The Array values:: ['random.randint(e, n) for_in range(n)']
The value of x = 96319
Start Time 1714035645.1142137
End time = 1714035645.1142657

2) Write a program to implement binary search algorithm.


Repeat the experiment for different values of n, the number
of elements in the list to be searched and plot a graph of time
taken versus n.

import time
import random
import matplotlib.pyplot as plt
def binary_search (arr, x):
low=0
high = 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
n_values=(10,100,1000,10000,100000)
times = []
for n in n_values:
arr= [random.randint(0,n) for _ in range (n)]
print("the value of n=",n)
print("The Array values::",arr)
x=random.randint(0,n)
print("the value of x=",x)
start_time=time.time()
print("start time = ",start_time)
binary_search(arr,x)
end_time=time.time()
print("End time=",end_time)
times.append(end_time - start_time)
plt.plot(n_values,times)
plt.xlabel('n')
plt.ylabel ("Time laken (seconds)")
plt.show()

output: the value of n= 10


The Array values:: [1, 10, 6, 10, 6, 3, 3, 4, 4, 7]
the value of x= 10
start time = 1717684584.3359158
End time= 1717684584.3671744
the value of n= 100
The Array values:: [4, 48, 32, 75, 26, 24, 12, 48, 56, 59, 38, 73, 94, 31, 2,
84, 4, 1, 90, 92, 26, 34, 90, 61, 97, 88, 59, 4, 71, 16, 26, 80, 9, 52, 74,
67, 49, 3, 90, 21, 92, 48, 3, 70, 15, 42, 73, 78, 96, 49, 85, 86, 21, 53, 72,
18, 83, 33, 53, 49, 84, 45, 43, 65, 77, 98, 64, 88, 11, 20, 54, 50, 71, 79,
24, 9, 86, 56, 74, 19, 96, 24, 47, 71, 71, 81, 76, 76, 90, 87, 71, 38, 23, 35,
46, 31, 5, 73, 40, 97]
the value of x= 73
start time = 1717684584.4452877
End time= 1717684584.4609168
the value of n= 1000
The Array values::
the value of x= 249
start time = 1717684584.570259
End time= 1717684584.570259
the value of n= 10000
The Array values::
the value of x= 2480
start time = 1717684585.11713
End time= 1717684585.132744
the value of n= 100000
The Array values::
the value of x= 19896
start time = 1717684590.5230072
End time= 1717684590.5386443

3) Write a program to solve the Towers of Hanoi problem and


execute it for different numbers of disks.

def move_disk(source,dest):
print(f"Move disk from {source}to{dest}")
def tower_of_hanoi(n,source,temp,dest):
if n==1:
move_disk(source,dest)
else:
tower_of_hanoi(n-1,source,dest,temp)
move_disk(source,dest)
tower_of_hanoi(n-1,temp,source,dest)
num_disks=int(input("Enter the number of disks:"))
tower_of_hanoi(num_disks,'A','B','C')

output: Enter the number of disks:4


Move disk from AtoB
Move disk from AtoC
Move disk from BtoC
Move disk from AtoB
Move disk from CtoA
Move disk from CtoB
Move disk from AtoB
Move disk from AtoC
Move disk from BtoC
Move disk from BtoA
Move disk from CtoA
Move disk from BtoC
Move disk from AtoB
Move disk from AtoC
Move disk from BtoC

4) Write a program to sort a given set of numbers using


selection sort algorithm. Repeat the experiment for different
values of n, the number of elements in the list to be sorted
and plot a graph of the time taken versus n. The elements
can be read from a file or can be generated using random
number generator

import time
import random
import matplotlib.pyplot as plt
def selection_sort(arr):
n = len(arr)
for i in range(0,n-1):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
n_values = [10, 100, 1000]
times = []
for n in n_values:
arr=['random.randint(0,n)for_in range(n)']
start_time = time.time()
selection_sort(arr)
end_time = time.time()
times.append(end_time-start_time)
plt.plot(n_values, times)
plt.xlabel('n')
plt.ylabel('Time taken (seconds)')
plt.show()

output:

5) Write a program to find the value of an where a and n are


integers using both a brute-force based algorithm and a
divide-and-conquer based algorithm.

def bruteforce(a, n):

result = 1
for i in range(n):
result*=a
return result
def divideconquer(a, n):
if n == 0:
return 1
elif n % 2 == 0:
return divideconquer(a*a, n//2)
else:
return a * divideconquer(a*a, (n-1)//2)

a = int(input('Enter a value for base:: '))


n = int(input('Enter a value for exponent:: ' ))
print(f"Brute-force method:{bruteforce(a, n)}")
print(f"Divide-and-conquer method:{divideconquer(a,n)}")

output: Enter a value for base:: 5


Enter a value for exponent:: 2
Brute-force method:25
Divide-and-conquer method:25
6) Write a program to sort a given set of numbers using quick sort
algorithm. Repeat the experiment for different values of n, the number
of elements in the list to be sorted and plot a graph of the time taken
versus n.

import time
import matplotlib.pyplot as plt
import random

def quicksort(arr):
if len(arr)<=1:
return arr
pivot=arr[0]
left=[x for x in arr[1:] if x <=pivot]
right=[x for x in arr[1:] if x >=pivot]
return quicksort(left)+[pivot]+quicksort(right)

n_values=[10,100,500,750,900]
time_taken=[]
for n in n_values:
arr=[i for i in range(n)]
#random.shuffle(arr)
start_time = time.time()
print(arr)
sorted_arr = quicksort(arr)
pass
end_time = time.time()
time_taken.append(end_time - start_time)
print(f"sorted {n} elements in {end_time-start_time:.6f} seconds")
plt.figure(figsize=(10,6))
plt.plot(n_values,time_taken)
plt.xlabel("number of elements(n)")
plt.ylabel("time taken (seconds)")
plt.title("quick sort performance")
plt.grid(True)
plt.show()

output: sorted 10 elements in 0.000026 seconds


sorted 100 elements in 0.000281 seconds
sorted 500 elements in 0.001883 seconds
sorted 750 elements in 0.002912 seconds
sorted 900 elements in 0.003361 seconds
7) Write a program to find binomial co-efficient C(n,k) [ where n and k are
integers and n > k ] using brute force algorithm and also dynamic
programming based algorithm.

def binomial_brute_force(n,k):

if k==0 or k==n:
return 1
else:
return binomial_brute_force(n-1,k-1)+binomial_brute_force(n-1,k)

def binomial_dynamic(n,k):
dp=[[0 for i in range(k+1)]for j in range(n+1)]
for i in range(n+1):
for j in range(min(i,k)+1):
if j ==0 or j==i:
dp[i][j]=1
else:
dp[i][j]=dp[i-1][j-1]+dp[i-1][j]
return dp[n][k]
n=eval(input("enter the n value::"))
k=eval(input("enter the k value::"))
print(f"Brute-force method:{binomial_brute_force(n,k)}")
print(f"Dynamic programming method:{binomial_dynamic(n,k)}")

output: enter the n value::5


enter the k value::2
Brute-force method:10
Dynamic programming method:10
8) write a program to implement Flyod’s algorithm and find the lengths of the
shortest paths from every pairs of vertices in a weighted graph

nv=4
INF=999

def floyd(G):
#dist = (list map(lambda p:list(map(lambda:q,p)),G))
dist=[row[:] for row in G]
for r in range(nv):
for p in range(nv):
for q in range(nv):
dist[p][q]=min(dist[p][q],dist[p][r]+dist[r][q])

sol(dist)
def sol(dist):
for p in range(nv):
for q in range(nv):
if(dist[p][q]==INF):
print("INF",end=" ")
else:
print(dist[p][q],end=" ")
print(" ")
G=[
[0,5,INF,INF],
[10,0,15,5],
[40,INF,0,15],
[45,INF,5,0]
]
floyd(G)

output:
0 5 15 10
10 0 10 5
40 45 0 15
45 50 5 0

9) 9)write a program to evaluate polynomial using brute-force algorithm and


using Horner’s rule and compare their performances
import time
import random
def brute_force(coeff,x):
#Brute force based algorithm for evaluating a polynomial
n=len(coeff)
result=0
for i in range(n):
result += coeff[i]*(x**(n-i-1))
return result
def horner(coeff,x):
#Horners rule for evaluating a polynomial
n=len(coeff)
result=coeff[n-1]
for i in range(n-1):
result=result*x+coeff[n-i-2]
return result
coeff = [random.randint(0,10) for _ in range (1000)]
x=2
t1=time.time()
brute_force(coeff,x)
t2=time.time()
t3=time.time()
horner(coeff,x)
t4=time.time()
print("Brute_force time:", t2-t1)
print("Horner's rule time:",t4-t3)

output:
Brute_force time: 0.015601873397827148
Horner's rule time: 0.0
10) write a program to solve the string matching problrm using Boyer-
Moore approach.
def boyer_moore(text,pattern):
m=len(pattern)
n=len(text)
bad_char=[-1]*256
for i in range(m):
bad_char[ord(pattern[i])]=i
s=0

while s<=n-m:
j=m-1
while j>=0 and pattern[j]==text[s+j]:
j=-1
if j<0:
print("pattern found at shift",s)
s+=m-bad_char[ord(text[s+m])] if s+m<n else 1
else:
s+=max(1,j-bad_char[ord(text[s+j])])

boyer_moore("ABAAABCD","ABC")

output:
pattern found at shift 4
11)Write a program to solve the string matching problem using KMP
algorithm.
def kmp_prefix_function(pattern):

pi=[0]*len(pattern)

k=0

for q in range(1,len(pattern)):

while k>0 and pattern[k]!=pattern[q]:

k=pi[k-1]

if pattern[k]==pattern[q]:

k +=1

pi[q]=k

return pi

def kmp(text,pattern):

pi=kmp_prefix_function(pattern)

i=0

j=0

while i<len(text)and j<len(pattern):

if text[i]==pattern[j]:

i+=1

j+=1

elif j>0:

j=pi[j-1]

else:

i+=1

if j==len(pattern):

print("pattern found at index",i-len(pattern))

text="ABAABABCD"

pattern="ABC"

kmp(text,pattern)

output:

pattern found at index 5


12) Write a program to implement the BFS traversal algorithm.

from collections import deque

def bfs(graph,start):
# create a queue for bfs
queue=deque([start])
# mark the start node as visited
visited={start}
# traverse the graph
while queue:
# dequeue a vertex from the queue
vertex=queue.popleft()
# print the vertex
print(vertex)
# enqueue all adjacent vertices that have not been visited
for adjacent in graph[vertex]:
if adjacent not in visited:
queue.append(adjacent)
visited.add(adjacent)
graph={
'A':['B','C','D','E'],
'B':['A','D','F'],
'C':['A','G'],
'D':['A','B','F'],
'E':['A','G'],
'F':['B','D'],
'G':['C','E']
}
start='A'
bfs(graph,start)

output: A
B
C
D
E
F
G
13) Write a program to find the minimum spanning tree of a
given graph using Prim's algorithm.

import sys

def prim(graph):
vertices = list(graph.keys())
visited = {vertices[0]}
edges = []
mst =[]
total_cost = 0
while len(visited)!=len(vertices):
min_edge=(None,None,sys.maxsize)
for u in visited:
for v,w in graph[u].items():
if v not in visited and w<min_edge[2]:
min_edge=(u,v,w)
edges.append(min_edge)
visited.add(min_edge[1])
total_cost+=min_edge[2]
for edge in edges:
mst.append((edge[0],edge[1],graph[edge[0]][edge[1]]))
return mst,total_cost
graph ={
'A':{'B':7,'C':8},
'B':{'A':7,'D':6,'C':3},
'C':{'A':8,'B':3,'D':4,'E':3},
'D':{'B':6,'C':4,'E':2,'F':5},
'E':{'C':3,'D':2,'F':2},
'F':{'D':5,'E':2}
}
mst,cost=prim(graph)
print("the minimumspanning tree is:",mst)
print("the cost of the minimum spanning tree is:",cost)

output: the minimumspanning tree is: [('A', 'B', 7), ('B', 'C', 3), ('C', 'E',
3), ('E', 'D', 2), ('E', 'F', 2)]
the cost of the minimum spanning tree is: 17
14(a) Write a program to obtain the topological ordering of vertices in a given
digraph.
def main():
n=int(input("enter the number of verices:"))
count=0
c=[[0 for _ in range(n)] for _ in range(n)]
indeg=[0]*n
flag=[0]*n
i,j,k=0,0,0

print("enter the cost matrix (row by row):")


for i in range(n):
row = input().split()
for j in range(n):
c[i][j]=int(row[j])

for i in range(n):
for j in range(n):
indeg[i] += c[j][i]

print("the topologocal order is:")


while count < n:
for k in range(n):
if indeg[k] == 0 and flag[k] == 0:
print(f"{k+1:3}", end=" ")
flag[k] = 1
count += 1
for i in range(n):
if c[k][i] == 1:
indeg[i] -= 1

return 0
if __name__ == "__main__":
main()
output:
enter the number of verices:5
enter the cost matrix (row by row):
00100
00100
00011
00001
00000
the topologocal order is:
1 2 3 4 5
14(b) Write a program to compute transitive closure of a given directed graph using Warshall’s
algorithm
def warshalls(c, n):
for k in range(n):
for i in range(n):
for j in range(n):
if c[i][j] or (c[i][k] and c[k][j]):
c[i][j] = 1

print("the transitive closure of the graph is:")


for i in range(n):
for j in range(n):
print(c[i][j], end=" ")
print()

def main():
n = int(input("enter the number of verticrs:"))
c = []
print("enter the adjacency cost matrix:")
for i in range(n):
row = list(map(int, input().split()))
c.append(row)
warshalls(c, n)

main()
output:

enter the number of verticrs:4


enter the adjacency cost matrix:
0100
0001
0000
1010
the transitive closure of the graph is:
1111
1111
0000
1 111
15)Write a program to find subset of a given set s={s1,s2,…..sn} of n positive integers whose sum is
equal to given positive integer d. For example if s={1,2,5,6,8} and d=9 then two solutions {1,2,6}. A
suitable message is to be displayed if given problem if given problem doesn’t have soluton.
def sum_of_subsets(s, k, r):
global count, x, w, d, i
x[k] = 1
if s + w[k] == d:
print("\nSubset %d = " % (count + 1), end=" ")
for i in range(k + 1):
if x[i]:
print("%d " % w[i], end=" ")
elif s + w[k] + w[k + 1] <= d:
sum_of_subsets(s + w[k], k + 1, r - w[k])
if s + r - w[k] >= d and s + w[k + 1] <= d:
x[k] = 0
sum_of_subsets(s, k + 1, r - w[k])

if __name__ == "__main__":
w = [0] * 10
x = [0] * 10
count = 0
i=0

n = int(input("ENter the number of elements:"))


print("enter the elementsin ascending order:")
for i in range(n):
w[i] = int(input())

d = int(input("enter the sum: "))

sum = 0
for i in range(n):
x[i] = 0
sum += w[i]

if sum < d or w[0] > d:


print("\nNo subset possible\n")
else:
sum_of_subsets(0, 0, sum)

output:
Enter the number of elements:4
enter the elementsin ascending order:
15
5
10
10
enter the sum: 20

Subset 1 = 15 5
Subset 1 = 10 10

You might also like