0% found this document useful (0 votes)
18 views22 pages

Daa Lab

The document contains code snippets for several algorithms including: 1. Huffman coding for data compression that uses a priority queue to build a Huffman tree. 2. Solving the n-queens problem using backtracking to place queens on a chessboard without attacking each other. 3. Binary search to search for a target value in a sorted array. 4. Quicksort, mergesort, randomized quicksort for sorting arrays efficiently. 5. Travelling salesman problem to find the shortest route between cities using permutations.

Uploaded by

vikas 5G9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views22 pages

Daa Lab

The document contains code snippets for several algorithms including: 1. Huffman coding for data compression that uses a priority queue to build a Huffman tree. 2. Solving the n-queens problem using backtracking to place queens on a chessboard without attacking each other. 3. Binary search to search for a target value in a sorted array. 4. Quicksort, mergesort, randomized quicksort for sorting arrays efficiently. 5. Travelling salesman problem to find the shortest route between cities using permutations.

Uploaded by

vikas 5G9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

#HUFFMAN CODING

import heapq

class node:

def __init__(self, freq, symbol, left=None, right=None):

self.freq = freq

self.symbol = symbol

self.left = left

self.right = right

self.huff = ''

def __lt__(self, nxt):

return self.freq < nxt.freq

def printNodes(node, val=''):

newVal = val + str(node.huff)

if(node.left):

printNodes(node.left, newVal)

if(node.right):

printNodes(node.right, newVal)

if(not node.left and not node.right):

print(f"{node.symbol} -> {newVal}")

chars = ['a', 'b', 'c', 'd', 'e', 'f']

freq = [ 5, 9, 12, 13, 16, 45]


nodes = []

for x in range(len(chars)):

heapq.heappush(nodes, node(freq[x], chars[x]))

while len(nodes) > 1:

left = heapq.heappop(nodes)

right = heapq.heappop(nodes)

left.huff = 0

right.huff = 1

newNode = node(left.freq+right.freq, left.symbol+right.symbol,


left, right)

heapq.heappush(nodes, newNode)

printNodes(nodes[0])
# n queens

global N

N=4

def printSolution(board):

for i in range(N):

for j in range(N):

print(board[i][j], end = " ")

print()

def isSafe(board, row, col):

for i in range(col):

if board[row][i] == 1:

return False

for i, j in zip(range(row, -1, -1),

range(col, -1, -1)):

if board[i][j] == 1:

return False

for i, j in zip(range(row, N, 1),

range(col, -1, -1)):

if board[i][j] == 1:

return False

return True
def solveNQUtil(board, col):

if col >= N:

return True

for i in range(N):

if isSafe(board, i, col):

board[i][col] = 1

if solveNQUtil(board, col + 1) == True:

return True

board[i][col] = 0

return False

def solveNQ():

board = [ [0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0] ]

if solveNQUtil(board, 0) == False:

print ("Solution does not exist")

return False
printSolution(board)

return True

solveNQ()
def binary_search(arr, low, high, x):

if high >= low:

mid = (high + low) // 2

if arr[mid] == x:

return mid

elif arr[mid] > x:

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

else:

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

return -1

print("enter the elements")

arr = list(map(int,input().split()))

x = int(input("enter the element to be searched\n"))

result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:

print("Element is present at index", str(result))

else:

print("Element is not present in array")

#recursive binary search


def partition(array, low, high):

pivot = array[high]

i = low - 1

for j in range(low, high):

if array[j] <= pivot:

i=i+1

(array[i], array[j]) = (array[j], array[i])

(array[i + 1], array[high]) = (array[high], array[i + 1])

return i + 1

def quickSort(array, low, high):

if low < high:

pi = partition(array, low, high)

quickSort(array, low, pi - 1)

quickSort(array, pi + 1, high)

print("enter the elements")

data = list(map(int,input().split()))

print("Unsorted Array")

print(data)

size = len(data)

quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')

print(data)

#recursive quick sort


#recursive merge sort

def mergeSort(arr):

if len(arr) > 1:

mid = len(arr)//2

L = arr[:mid]

R = arr[mid:]

mergeSort(L)

mergeSort(R)

i=j=k=0

while i < len(L) and j < len(R):

if L[i] <= R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

j += 1

k += 1

while i < len(L):

arr[k] = L[i]

i += 1

k += 1
while j < len(R):

arr[k] = R[j]

j += 1

k += 1

print("enter the elements")

arr = list(map(int,input().split()))

mergeSort(arr)

print(*arr)
#randomized quick sort

import random

def quicksort(arr, start , stop):

if(start < stop):

pivotindex = partitionrand(arr,\

start, stop)

quicksort(arr , start , pivotindex-1)

quicksort(arr, pivotindex + 1, stop)

def partitionrand(arr , start, stop):

randpivot = random.randrange(start, stop)

arr[start], arr[randpivot] = \

arr[randpivot], arr[start]

return partition(arr, start, stop)


def partition(arr,start,stop):

pivot = start

i = start + 1

for j in range(start + 1, stop + 1):

if arr[j] <= arr[pivot]:

arr[i] , arr[j] = arr[j] , arr[i]

i=i+1

arr[pivot] , arr[i - 1] =\

arr[i - 1] , arr[pivot]

pivot = i - 1

return (pivot)

print("enter the elements")

arr = list(map(int,input().split()))

quicksort(arr, 0, len(arr) - 1)

print(*arr)
# TRAVELLING SALESPERSON

from sys import maxsize

from itertools import permutations

V=4

def travellingSalesmanProblem(graph, s):

vertex = []

for i in range(V):

if i != s:

vertex.append(i)

min_path = maxsize

next_permutation=permutations(vertex)

for i in next_permutation:

current_pathweight = 0

k=s

for j in i:

current_pathweight += graph[k][j]

k=j

current_pathweight += graph[k][s]

min_path = min(min_path, current_pathweight)

return min_path

if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],[15, 35, 0, 30], [20, 25,
30, 0]]

s=0

print(travellingSalesmanProblem(graph, s))
#sum of subsets

def isSubsetSum(set, n, sum) :

# Base Cases

if (sum == 0) :

return True

if (n == 0 and sum != 0) :

return False

if (set[n - 1] > sum) :

return isSubsetSum(set, n - 1, sum);

return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1,


sum-set[n-1])

set = [3, 34, 4, 12, 5, 2]

sum = 9

n = len(set)

if (isSubsetSum(set, n, sum) == True) :

print("Found a subset with given sum")

else :

print("No subset with given sum")


#all pairs shortest path

INF = 99999

def floyd_warshall(graph, V):

dist = [[0 for i in range(V)]

for i in range(V)]

for i in range(V):

for j in range(V):

dist[i][j] = graph[i][j]

for k in range(V):

for i in range(V):

for j in range(V):

if (dist[i][k] + dist[k][j] < dist[i][j]):

dist[i][j] = dist[i][k] + dist[k][j]

sum = 0

for i in range(V):

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

sum += dist[i][j]
return sum

def sumOfshortestPath(N, E,edges):

g = [[INF for i in range(N)]

for i in range(N)]

for i in range(E):

u = edges[i][0]

v = edges[i][1]

w = edges[i][2]

g[u][v] = w

g[v][u] = w

return floyd_warshall(g, N)

if __name__ == '__main__':

N=4

E=3

Edges = [ [ 0, 1, 1 ],[ 1, 2, 2 ],[ 2, 3, 3 ] ]

print(sumOfshortestPath(N, E, Edges))

#single source shortest path algorithm


import sys

class Graph():

def __init__(self, vertices):

self.V = vertices

self.graph = [[0 for column in range(vertices)]

for row in range(vertices)]

def printSolution(self, dist):

print("Vertex \tDistance from Source")

for node in range(self.V):

print(node, "\t", dist[node])

def minDistance(self, dist, sptSet):

min = sys.maxsize

for u in range(self.V):

if dist[u] < min and sptSet[u] == False:

min = dist[u]

min_index = u

return min_index

def dijkstra(self, src):


dist = [sys.maxsize] * self.V

dist[src] = 0

sptSet = [False] * self.V

for cout in range(self.V):

x = self.minDistance(dist, sptSet)

sptSet[x] = True

for y in range(self.V):

if self.graph[x][y] > 0 and sptSet[y] == False


and \

dist[y] > dist[x] + self.graph[x][y]:

dist[y] = dist[x] + self.graph[x][y]

self.printSolution(dist)

if __name__ == "__main__":

g = Graph(9)

g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],

[4, 0, 8, 0, 0, 0, 0, 11, 0],

[0, 8, 0, 7, 0, 4, 0, 0, 2],

[0, 0, 7, 0, 9, 14, 0, 0, 0],

[0, 0, 0, 9, 0, 10, 0, 0, 0],


[0, 0, 4, 14, 10, 0, 2, 0, 0],

[0, 0, 0, 0, 0, 2, 0, 1, 6],

[8, 11, 0, 0, 0, 0, 1, 0, 7],

[0, 0, 2, 0, 0, 0, 6, 7, 0]

g.dijkstra(0)

#implement kanpsack
def knapSack(W, wt, val, n):

if n == 0 or W == 0 :

return 0

if (wt[n-1] > W):

return knapSack(W, wt, val, n-1)

else:

return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),

knapSack(W, wt, val, n-1))

val = [60, 100, 120]

wt = [10, 20, 30]

W = 50

n = len(val)

print knapSack(W, wt, val, n)


# 0/1 knapsack

def knapSack(W, wt, val, n):

K = [[0 for x in range(W + 1)] for x in range(n + 1)]

for i in range(n + 1):

for w in range(W + 1):

if i == 0 or w == 0:

K[i][w] = 0

elif wt[i-1] <= w:

K[i][w] = max(val[i-1]

+ K[i-1][w-wt[i-1]],

K[i-1][w])

else:

K[i][w] = K[i-1][w]

return K[n][W]

val = [60, 100, 120]

wt = [10, 20, 30]

W = 50

n = len(val)

print(knapSack(W, wt, val, n)

You might also like