0% found this document useful (0 votes)
7 views30 pages

Ada Manual

The document contains seven separate programs implementing various algorithms including linear search, binary search, Towers of Hanoi, selection sort, power calculation, quick sort, and binomial coefficient calculation. Each program includes input prompts, algorithm implementations, and performance measurement with time plotting. The outputs demonstrate the functionality of each program through user interactions and results.

Uploaded by

sumanthno17
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)
7 views30 pages

Ada Manual

The document contains seven separate programs implementing various algorithms including linear search, binary search, Towers of Hanoi, selection sort, power calculation, quick sort, and binomial coefficient calculation. Each program includes input prompts, algorithm implementations, and performance measurement with time plotting. The outputs demonstrate the functionality of each program through user interactions and results.

Uploaded by

sumanthno17
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/ 30

PROGRAM 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 the time taken versus n.

import timeit

import matplotlib.pyplot as plt

# Input Array elements

def Input(Array, n):

# iterating till the range

for i in range(0, n):

ele = int(input(f"Arr[{i+1}]: ")) # Added index to the prompt for clarity

# adding the element

Array.append(ele)

# Linear Searching

def linear_search(Array, key):

for x in Array:

if x == key:

return True

return False

# Main Block()

if __name__ == "__main__": # Ensures the following code runs only when the script is executed
directly

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:", Array) #Added array label to identify array elements

key = int(input("Enter key to search: ")) #changed the input line to identify the 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)

# naming the x axis

plt.xlabel('Array Size - N')

# naming the y axis

plt.ylabel('CPU Processing Time (microseconds)') #added units to make it more clear

# giving a title to graph

plt.title('Linear Search Time efficiency')

# function to show the plot

plt.show()

OUTPUT:

Enter no. of trails : 2

-----> TRAIL NO : 1

Enter number of elements : 4

Arr[1]: 23

Arr[2]: 34
Arr[3]: 45

Arr[4]: 67

Array: [23, 34, 45, 67]

Enter key to search: 45

Element Found = True

-----> TRAIL NO : 2

Enter number of elements : 4

Arr[1]: 34

Arr[2]: 56

Arr[3]: 78

Arr[4]: 90

Array: [34, 56, 78, 90]

Enter key to search: 10

Element Found = False

N CPU

4 86.9

4 124.2

PROGRAM 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 the time taken versus n.

import timeit

import matplotlib.pyplot as plt


# Input Array elements

def Input(Array, n):

# iterating till the range

for i in range(0, n):

ele = int(input(f"Arr[{i+1}]: "))

# adding the element

Array.append(ele)

# Binary Searching

def binary_search(Array, key):

Array.sort() #Crucial: Binary search requires a sorted array

low = 0

high = len(Array) - 1

while low <= high:

mid = (low + high) // 2

if Array[mid] == key:

return True

elif Array[mid] < key:

low = mid + 1 #Search in the right half

else:

high = mid - 1 #Search in the left half

return False

# Main Block()

if __name__ == "__main__":

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:", Array)

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

start = timeit.default_timer()

s = binary_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)

# naming the x axis

plt.xlabel('Array Size - N')

# naming the y axis

plt.ylabel('CPU Processing Time (microseconds)')

# giving a title to graph

plt.title('Binary Search Time efficiency')

# function to show the plot

plt.show()

OUTPUT:

Enter no. of trails : 2

-----> TRAIL NO : 1
Enter number of elements : 6

Arr[1]: 10

Arr[2]: 20

Arr[3]: 30

Arr[4]: 40

Arr[5]: 50

Arr[6]: 60

Array: [10, 20, 30, 40, 50, 60]

Enter key : 45

Element Found = False

-----> TRAIL NO : 2

Enter number of elements : 5

Arr[1]: 45

Arr[2]: 67

Arr[3]: 89

Arr[4]: 54

Arr[5]: 56

Array: [45, 67, 89, 54, 56]

Enter key : 89

Element Found = True

N CPU

6 92.0

5 102.6
PROGRAM 3: write a program to solve towers of Hanoi problem and execute it for different number of
disks.

# Recursive Python function to solve the Tower of Hanoi

def TowerOfHanoi(n, source, destination, auxiliary):

if n == 1:

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

return

TowerOfHanoi(n - 1, source, auxiliary, destination)

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

TowerOfHanoi(n - 1, auxiliary, destination, source)

# Main Block

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

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

OUTPUT:

Enter number of disks: 3

Move disk 1 from source A to destination B

Move disk 2 from source A to destination C

Move disk 1 from source B to destination C

Move disk 3 from source A to destination B


Move disk 1 from source C to destination A

Move disk 2 from source C to destination B

Move disk 1 from source A to destination B

PROGRAM 4: write a program to sort a given set of number using selection sort algorithm. Repeat the
experiment for different values of n, the number of elements can be read from a file or can be generated
using the random number generator

import timeit

import random

import matplotlib.pyplot as plt

# Input Array elements

def Input(Array, n):

# iterating till the range

for i in range(0, n):

ele = random.randrange(1, 50)

# adding the element

Array.append(ele)

# Selection Sort

def selectionSort(Array, size):

for ind in range(size):

min_index = ind

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

# select the minimum element in every iteration

if Array[j] < Array[min_index]:

min_index = j

# swapping the elements to sort the array

(Array[ind], Array[min_index]) = (Array[min_index], Array[ind])

# Main Block()
if __name__ == "__main__":

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)

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) * 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)

# naming the x axis

plt.xlabel('Array Size - N')

# naming the y axis

plt.ylabel('CPU Processing Time (microseconds)')

# giving a title to graph

plt.title('Selection Sort Time efficiency')

# function to show the plot


plt.show()

OUTPUT:

Enter no. of trails : 2

-----> TRAIL NO : 1

Enter number of elements : 8

Sorted Array :

[3, 14, 24, 29, 32, 32, 33, 34]

-----> TRAIL NO : 2

Enter number of elements : 6

Sorted Array :

[10, 11, 14, 21, 46, 49]

N CPU

8 10.9

6 5.1

PROGRAM 5: write a program to find the value of an (where a and n are integers) using both brute-force
based algorithm and Divide and Conquer based algorithm

# Brute force method

# A simple solution to calculate pow(a, n) would multiply a exactly n times.

def bpower(a, n):

pow = 1
for i in range(n):

pow = pow * a

return pow

# Divide and Conquer method

# The problem can be recursively defined by:

# dpower(x, n) = dpower(x, n / 2) * dpower(x, n / 2); // if n is even

# dpower(x, n) = x * dpower(x, n / 2) * dpower(x, n / 2); // if n is odd

def dpower(x, y):

if y == 0:

return 1

elif y % 2 == 0: # Check if y is even

half_power = dpower(x, y // 2)

return half_power * half_power

else: # y is odd

half_power = dpower(x, y // 2)

return x * half_power * half_power

# Main block

if __name__ == "__main__":

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

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

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

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

OUTPUT:

Enter a: 2

Enter n: 10

Brute Force method a^n: 1024

Divide and Conquer method a^n: 1024


PROGRAM 6: write a program to sort a given set of elements 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):

# iterating till the range

for i in range(0, n):

ele = random.randrange(1, 50)

# adding the element

Array.append(ele)

# divide function

def partition(Array, low, high):

i = (low - 1)

pivot = Array[high] # pivot element

for j in range(low, high):

# If current element is smaller than or equal to pivot

if Array[j] <= pivot:

# increment

i=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:


# index

pi = partition(Array, low, high)

# sort the partitions

quickSort(Array, low, pi - 1)

quickSort(Array, pi + 1, high)

# Main Block

N = []

CPU = []

trail = int(input("Enter number of trials: ")) # corrected typo from "trails" to "trials"

for t in range(0, trail):

Array = []

print("-----> TRAIL 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)) # Convert seconds to microseconds

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)

# Naming the x axis

plt.xlabel('Array Size - N')

# Naming the y axis

plt.ylabel('CPU Processing Time (microseconds)')

# Giving a title to graph

plt.title('Quick Sort Time Efficiency')

# Function to show the plot

plt.show()

OUTPUT:

Enter number of trials: 3

-----> TRAIL NO: 1

Enter number of elements: 6

Sorted Array:

[3, 9, 20, 25, 28, 28]

-----> TRAIL NO: 2

Enter number of elements: 7

Sorted Array:

[4, 7, 7, 9, 10, 20, 29]

-----> TRAIL NO: 3

Enter number of elements: 4

Sorted Array:

[8, 33, 42, 47]

N CPU

6 21.7

7 7.7

4 7.1
PROGRAM 7: write a program to find the binomial co-efficient C(n, k),[where n and k are integers and n>k]
using Brute force based algorithm and also dynamic programming based algorithm

# Brute force method

# The value of C(n, k) can be recursively calculated using the standard formula for Binomial
Coefficients.

# C(n, k) = C(n-1, k-1) + C(n-1, k)

# C(n, 0) = C(n, n) = 1

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)

# Divide and Conquer method

# Re-computations of the same subproblems can be avoided by constructing a temporary 2D-array


C[][] in a bottom-up manner.

# Uses Overlapping Subproblems concept

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

# Calculate value using previously stored values

else:

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 C({}, {}) : {}".format(n, k, binomialCoeff_BF(n, k)))

print("Divide and Conquer method C({}, {}) : {}".format(n, k, binomialCoef_DC(n, k)))

OUTPUT:

Enter n: 5

Enter k: 3

Brute Force method C(5, 3) : 10

Divide and Conquer method C(5, 3) : 10

PROGRAM 8: write a program to implement Floyd’s algorithm and find the lengths of the shortest paths
from every pairs of vertices in a given weighted graph

# Number of vertices

nV = 4

INF = float('inf') # Use a more appropriate representation for infinity

# Algorithm

def floyd(G):

# Initialize distance matrix


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() # Move to the next line after each row

# Input graph represented as an adjacency matrix

G=[

[0, 5, INF, INF],

[50, 0, 15, 5],

[30, INF, 0, 15],

[15, INF, 5, 0]

floyd(G)

OUTPUT:

0 5 15 10
20 0 10 5

30 35 0 15

15 20 5 0

PROGRAM 9: write a program to evaluate a polynomial using brute-force based algorithm and using
Horner’s rule and compare their performances

import timeit

def polynomial_BF(poly, x, n):

"""

Calculates the value of a polynomial using the 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 2x3 - 6x2 + 2x - 1 for x = 3 using [BRUTE FORCE method]:", result)

def horner(poly, x, n):

"""

Calculates the value of a polynomial using Horner's method.

"""

res = poly[0]

for i in range(1, n):

res = res * x + poly[i]

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

# Main block

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 method O(n):", t2)

OUTPUT:

Value of polynomial 2x3 - 6x2 + 2x - 1 for x = 3 using [BRUTE FORCE method]: 5

Value of polynomial 2x3 - 6x2 + 2x - 1 for x = 3 using [HORNER method]: 5

Time complexity of Brute force method O(n^2): 0.0004072000738233328

Time complexity of Horner method O(n): 0.00012599979527294636

PROGRAM 10: write a program to solve the string matching problem using Boyer-Moore approach.

def BoyerMooreHorspool(pattern, text):

m = len(pattern)

n = len(text)

if m > n:

return -1

# Create the skip table

skip = []

for k in range(256):

skip.append(m)
for k in range(m - 1):

skip[ord(pattern[k])] = m - k - 1

skip = tuple(skip)

k = m - 1 # Start with the end of the pattern

while k < n:

j = m - 1 # Start comparing from the end of the pattern

i=k # Position in text

while j >= 0 and text[i] == pattern[j]:

j -= 1

i -= 1

if j == -1: # Match found

return i + 1

k += skip[ord(text[k])] # Move to the next character in text

return -1 # No match found

# Main block

if __name__ == '__main__':

text = "this is the string to search in"

pattern = "the"

s = BoyerMooreHorspool(pattern, text)

print('Text:', text)

print('Pattern:', pattern)

if s > -1:
print('Pattern "' + pattern + '" found at position', s)

else:

print('Pattern "' + pattern + '" not found.')

OUTPUT:

Text: this is the string to search in

Pattern: the

Pattern "the" found at position 8

PROGRAM 11: write a program to solve the string matching problem using KMP algorithm

def KMP_Pattern_Search(pattern, text):

# Preprocess the pattern to create the longest prefix suffix (LPS) array

m = len(pattern)

n = len(text)

# Create LPS array

lps = [0] * m

j = 0 # Length of previous longest prefix suffix

computeLPSArray(pattern, m, lps)

initial_index = [] # List to store the starting indices of matches

i = 0 # Index for text

while i < n:

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

i += 1

j += 1

if j == m: # A match is found

initial_index.append(i - j) # Append the starting index of the match

j = lps[j - 1] # Get the next character to compare


elif i < n and pattern[j] != text[i]: # Mismatch after j matches

if j != 0:

j = lps[j - 1]

else:

i += 1

return initial_index

def computeLPSArray(pattern, m, lps):

length = 0 # Length of previous longest prefix suffix

i=1

while i < m:

if pattern[i] == pattern[length]:

length += 1

lps[i] = length

i += 1

else:

if length != 0:

length = lps[length - 1]

else:

lps[i] = 0

i += 1

# Main module

if __name__ == "__main__":

string = "ABABDABACDABABCABABCABAB"

pat = "ABABCABAB"

initial_index = KMP_Pattern_Search(pat, string)


print("String:", string)

print("Pattern:", pat)

if initial_index:

for i in initial_index:

print('Pattern is found in the string at index number', i)

else:

print('Pattern not found in the string.')

OUTPUT:

string: ABABDABACDABABCABABCABAB

Pattern: ABABCABAB

Pattern is found in the string at index number 10

Pattern is found in the string at index number 15

PROGRAM 12: write a program to implement BFS traversal algorithm.

# Define the graph as an adjacency list

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) # Dequeue a vertex from the queue

print(m, end=" ") # Print the visited node

for neighbour in graph[m]: # Iterate through all neighbours of the dequeued node

if neighbour not in visited: # If neighbour hasn't been visited

visited.append(neighbour) # Mark it as visited

queue.append(neighbour) # Enqueue it

# Main module

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

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

OUTPUT:

Following is the breadth-first search:

5 3 7 2 4 8

PROGRAM 13: write a program to find the minimum spanning tree of a given graph using prim’s algorithm

# Prim's Algorithm in Python

INF = 9999999

V=5

G=[

[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]

# Initialize selected array to track vertices included in MST

selected = [False] * V
no_edge = 0

# Start from the first vertex

selected[0] = True

print("Edge : Weight\n")

while no_edge < V - 1:

minimum = INF

x=0

y=0

for i in range(V):

if selected[i]: # If vertex i is included in MST

for j in range(V):

# Check for edges from i to j that are not yet included in MST

if not selected[j] and G[i][j]:

# Update minimum if a smaller edge is found

if minimum > G[i][j]:

minimum = G[i][j]

x=i

y=j

print(f"{x} - {y} : {G[x][y]}") # Print the edge and its weight

selected[y] = True # Include vertex y in MST

no_edge += 1 # Increment count of edges included

OUTPUT:

Edge : Weight

0-1:2

1-2:3

1-4:5
0-3:6

PROGRAM 14: write a program to obtain the topological ordering of vertices in a given digraph. Compute
the transitive closure of a given directed graph using Warshall’s algorithm

# Python program for transitive closure using Floyd Warshall Algorithm

# Complexity: O(V^3)

from collections import defaultdict

# Class to represent a graph

class Graph:

def __init__(self, vertices):

self.V = vertices

# A 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):

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

print() # Move to the next line after each row

# Prints transitive closure of graph using Floyd Warshall algorithm

def transitiveClosure(self, graph):

# Initialize reachability matrix

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)

OUTPUT:

Following matrix transitive closure of the given graph:

1 1 1 1

0 1 1 1

0 0 1 1

0 0 0 1

PROGRAM 15: write a program to find a subset of a given set S={s1,s2,sn} of n positive integers whose....
sum is equal to a given positive integer d. For example, if S={1,2,5,6,8} and d=9 there are two solutions
{1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesn’t have a
solution.

from itertools import combinations

def Input(S, n):

# Iterating till the range

for i in range(n):

ele = int(input("Arr: ")) # Prompt for array element

# Adding the element

S.append(ele)

def sub_set_sum(size, S, d):

count = 0
# Check all possible subsets

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)) # Print the subset that sums to d

count += 1

if count == 0:

print("Subset Not found for the given d =", d)

# Main module

S = []

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

Input(S, n)

print("Input set:", S)

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

print("The result is:")

sub_set_sum(n, S, d)

OUTPUT:

Enter size: 4

Arr: 1

Arr: 2

Arr: 3

Arr: 4

Input set: [1, 2, 3, 4]

Enter sum d: 5

The result is:

[1, 4]

[2, 3]

When No subset matches:

Enter size: 3
Arr: 1

Arr: 2

Arr: 5

Input set: [1, 2, 5]

Enter sum d: 20

The result is:

Subset Not found for the given d = 20

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