0% found this document useful (0 votes)
3 views14 pages

DAA Lab Programs banglore university buc

The document contains a series of programming tasks, each implementing different algorithms such as linear search, binary search, sorting algorithms, and graph algorithms. Each task includes code snippets, input methods, and performance evaluation through time measurement and plotting. The document serves as a comprehensive guide for learning and experimenting with various algorithmic concepts in programming.

Uploaded by

23d3092
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)
3 views14 pages

DAA Lab Programs banglore university buc

The document contains a series of programming tasks, each implementing different algorithms such as linear search, binary search, sorting algorithms, and graph algorithms. Each task includes code snippets, input methods, and performance evaluation through time measurement and plotting. The document serves as a comprehensive guide for learning and experimenting with various algorithmic concepts in programming.

Uploaded by

23d3092
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/ 14

DAA LAB PROGRAMS

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 timeit

import matplotlib.pyplot as plt

#Input Array Elements

def Input(Array,n):

for i in range(0,n):

ele=int(input("Arr:"))

Array.append(ele)

#Linear searching

def linear_search(Array,key):

for x in Array:

if x==key:

return True

return False

#Main Block

N=[]

CPU=[]

trail=int(input("Enter No. of trails:"))

for t in range(0,trail):

Array=[]

print("----->TRAIL NO:",t+1)

n= int(input("Enter number of elements:"))

Input(Array,n)

print(Array)

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

start=timeit.default_timer()

s=linear_search(Array,key)

print("Element Found=",s)

times=timeit.default_timer()-start
N.append(n)

CPU.append(round(float(times)*1000000,2))

print("N CPU")

for t in range(0,trail):

print(N[t],CPU[t])

#plotting Graph

plt.plot(N,CPU)

plt.scatter(N,CPU,color="red",marker="*",s=50)

plt.xlabel('Array Size-n')

plt.ylabel('CPU Processing Time')

plt.title('Linear Search Time efficiency')

plt.show()

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 timeit

import matplotlib.pyplot as plt

def Input(Array,n):

for i in range(0,n):

ele=int(input("Arr:"))

Array.append(ele)

#Binary searching

def binary_search(Array,x,low,high):

if high>=low:

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

if Array[mid]==x:

return mid

elif Array[mid]>x:

return binary_search(Array,x,low,mid-1)

else:

return binary_search(Array,x,mid+1,high)

else:
return-1

#Main Block

N=[]

CPU=[]

trail=int(input("Enter No. of trails:"))

for t in range(0,trail):

Array=[]

print("----->TRAIL NO:",t+1)

n= int(input("Enter number of elements:"))

Input(Array,n)

print(Array)

x=int(input("Enter key:"))

start=timeit.default_timer()

s=binary_search(Array,x,0,len(Array)-1)

print("Element Found=",s+1)

times=timeit.default_timer()-start

N.append(n)

CPU.append(round(float(times)*1000000,2))

print("N CPU")

for t in range(0,trail):

print(N[t],CPU[t])

#plotting Graph

plt.plot(N,CPU)

plt.scatter(N,CPU,color="red",marker="*",s=50)

plt.xlabel('Array Size-N')

plt.ylabel('CPU Processing Time')

plt.title('Binary Search Time efficiency')

plt.show()

3. Write a program to solve towers of Hanoi problem and execute it for different number of disks
def TowerOfHonai(n, source, destination, auxillary):

if n==1:

print("Move disk 1 from source", source, "to destination", destination)


return

TowerOfHonai(n - 1, source, auxillary, destination)

print("Move disk", n, "from source", source, "to destination", destination)

TowerOfHonai(n - 1, auxillary, destination, source)

#main block

n=int(input("Enter number of disk:"))

TowerOfHonai(n, 'A', 'B','C')

#A, B, C are the names of rods

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.
import timeit

import random

import matplotlib.pyplot as plt

#Input Array elements

def Input(Array,n):

for i in range(0,n):

ele=random.randrange(1,50)

Array.append(ele)

#Selection Sort

def selectionSort(Array,size):

for i in range(size):

Min=i

for j in range(i+1,size):

if Array[j]<Array[Min]:

Min=j

(Array[i],Array[Min])=(Array[Min],Array[i])

#Main Block
N=[]

CPU=[]

trial=int(input("Enter no. of trials:"))

for t in range(0,trial):

Array=[]

print("--->TRIAL NO:",t+1)

n=int(input("Enter no. of elements:"))

Input(Array,n)

print(Array)

start=timeit.default_timer()

selectionSort(Array,n)

times=timeit.default_timer()-start

print("Sorted Array:")

print(Array)

N.append(n)

CPU.append(round(float(times)*100000,2))

print("N CPU")

for t in range(0,trial):

print(N[t],CPU[t])

#Plotting Graph

plt.plot(N,CPU)

plt.scatter(N,CPU,color="red",marker="*",s=50)

plt.xlabel("Array Size(N)")

plt.ylabel("CPU Processing Time")

plt.title("Selection sort Time Efficiency")

plt.show()

5. Write a program to find an using (a) Brute-force based algorithm (b) Divide and conquer based
algorithm
def bpower(a, n):

pow=1
for i in range(n):

pow=pow*a

return pow

def dpower(x, y):

if(y==0):

return 1

elif(int(y%2)==0):

return(dpower(x, int(y/2))*dpower(x, int(y/2)))

else:

return(x*dpower(x, int(y/2))*dpower(x, int(y/2)))

#main block

a=int(input("Enter a:"))

n=int(input("Enter n:"))

print("Brute Force method a^n:",bpower(a,n))

print("Divide and conquer a^n:",dpower(a,n))

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 timeit

import random

import matplotlib.pyplot as plt

# Input Array elements

def Input(Array, n):

for i in range(0, n):

ele = random.randrange(1, 50)

Array.append(ele)

# Partition function

def partition(Array, low, high):

i = low - 1

pivot = Array[high]
for j in range(low, high):

if Array[j] <= pivot:

i += 1

Array[i], Array[j] = Array[j], Array[i]

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

return i + 1

# Quick Sort function

def quickSort(Array, low, high):

if low < high:

pi = partition(Array, low, high)

quickSort(Array, low, pi - 1)

quickSort(Array, pi + 1, high)

# Main Block

N = []

CPU = []

trail = int(input("Enter no. of trials: "))

for t in range(0, trail):

Array = []

print("-----> TRIAL NO:", t + 1)

n = int(input("Enter number of elements: "))

Input(Array, n)

start = timeit.default_timer()

quickSort(Array, 0, n - 1)

times = timeit.default_timer() - start

print("Sorted Array:")

print(Array)
N.append(n)

CPU.append(round(float(times) * 1000000, 2))

# Display results

print("N\tCPU")

for t in range(0, trail):

print(f"{N[t]}\t{CPU[t]}")

# Plotting Graph

plt.plot(N, CPU)

plt.scatter(N, CPU, color="red", marker="*", s=50)

plt.xlabel('Array Size - N')

plt.ylabel('CPU Processing Time (µs)')

plt.title('Quick Sort Time Efficiency')

plt.show()

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 binomialCoeff_BF(n, k):

if k > n:

return 0

if k == 0 or k == n:

return 1

# Recursive call

return binomialCoeff_BF(n - 1, k - 1) + binomialCoeff_BF(n - 1, k)

def binomialCoef_DC(n, k):

C = [[0 for x in range(k + 1)] for x in range(n + 1)]

# Calculate value of Binomial Coefficient in bottom-up manner

for i in range(n + 1):

for j in range(min(i, k) + 1):

# Base cases
if j == 0 or j == i:

C[i][j] = 1

else:

# Use previously stored values

C[i][j] = C[i - 1][j - 1] + C[i - 1][j]

return C[n][k]

# Main Block

n = int(input("Enter n: "))

k = int(input("Enter k: "))

print("Brute Force method n^k:", binomialCoeff_BF(n, k))

print("Divide and Conquer n^k:", binomialCoef_DC(n, k))

8. Write a program to implement Floyd’s algorithm and find the lengths of the shortest paths from every
pair of vertices in a weighted graph.
# Number of vertices

nV = 4

INF = 999

# Algorithm

def floyd(G):

dist = list(map(lambda p: list(map(lambda q: q, p)), G))

# Adding vertices individually

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)

# Printing the output

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(" ")

# Input

G = [[0, 5, INF, INF],

[50, 0, 15, 5],

[30, INF, 0, 15],

[15, INF, 5, 0]]

floyd(G)

9. Write a program to evaluate polynomial using brute-force algorithm and using Horner’s rule and
compare their performances.
import timeit

def polynomial_BF(poly, x, n):

# Brute Force Method

result = 0

for i in range(n):

Sum = poly[i]

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

Sum = Sum * x

result = result + Sum

print("Value of polynomial 2x^3 - 6x^2 + 2x - 1 for x = 3 using [BRUTE FORCE method]:", result)

def horner(poly, x, n):

# Horner's Method

res = poly[0]

for i in range(1, n):

res = res * x + poly[i]


print("Value of polynomial 2x^3 - 6x^2 + 2x - 1 for x = 3 using [HORNER method]:", res)

# Main Block

# Evaluating polynomial: 2x^3 - 6x^2 + 2x - 1 for x = 3

poly = [2, -6, 2, -1]

x=3

n = len(poly)

start1 = timeit.default_timer()

polynomial_BF(poly, x, n)

t1 = timeit.default_timer() - start1

start2 = timeit.default_timer()

horner(poly, x, n)

t2 = timeit.default_timer() - start2

print("Time complexity of Brute Force method O(n^2):", t1)

print("Time complexity of Horner's method O(n):", t2)

10. Write a program to implement BFS traversal algorithm.


graph = {

'5' : ['3','7'],

'3' : ['2', '4'],

'7' : ['8'],

'2' : [],

'4' : ['8'],

'8' : []

visited = [] # List for visited nodes.

queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS

visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node

m = queue.pop(0)

print (m, end = " ")

for neighbour in graph[m]:

if neighbour not in visited:

visited.append(neighbour)

queue.append(neighbour)

# Driver Code

print("Following is the Breadth-First Search")

bfs(visited, graph, '5') # function calling

11. Write a program to obtain the transitive closure of a given directed graph using Warshall’s algorithm.
# Class to represent a graph

class Graph:

def __init__(self, vertices):

self.V = vertices

# Utility function to print the solution

def printSolution(self, reach):

print("Following matrix transitive closure of the given graph")

for i in range(self.V):

for j in range(self.V):

if i == j:

print("%7d\t" % 1, end=" ")

else:

print("%7d\t" % reach[i][j], end=" ")

print()

# Computes transitive closure using Floyd-Warshall algorithm

def transitiveClosure(self, graph):

# Initialize reach matrix same as input graph


reach = [i[:] for i in graph]

for k in range(self.V):

for i in range(self.V):

for j in range(self.V):

reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j])

self.printSolution(reach)

# Main module

g = Graph(4)

graph = [

[1, 1, 0, 1],

[0, 1, 1, 0],

[0, 0, 1, 1],

[0, 0, 0, 1]

# Print the solution

g.transitiveClosure(graph)

12. . 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.
from itertools import combinations

def Input(S, n):

for i in range(0, n):

ele=int(input("Arr : "))

S.append(ele)

def sub_set_sum(size, S, sub_set_sum):

count=0

for i in range(size+1):

for my_sub_set in combinations(S, i):

if sum(my_sub_set) == d:

print(list(my_sub_set))

count=count+1

if(count==0):
print("Subset Not found for the given d=",d)

#main block

S=[]

n=int(input("Enter Size:"))

Input(S, n)

print(S)

d= int(input("Enter sum d :"))

print("The result is:")

sub_set_sum(n, S, d)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy