0% found this document useful (0 votes)
13 views7 pages

#1 Selection Sort # Changed To Positive Infinity For Correct Comparison

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)
13 views7 pages

#1 Selection Sort # Changed To Positive Infinity For Correct Comparison

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

5/5/24, 10:24 PM Assgn3

In [3]: #1 Selection sort


def selectionSort(arr):
for i in range(len(arr)):
min = float('inf') # Changed to positive infinity for correct comparison
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr # Moved return statement outside the inner loop

arr = list(map(int, input("Enter the array elements separated by space: ").split()))


print(selectionSort(arr))

Enter the array elements separated by space: 89 56 45 34 65


[34, 45, 56, 65, 89]

In [5]: #2
import sys

def greedy_search(graph, source):


distances = {node: sys.maxsize for node in graph}
distances[source] = 0
unvisited = set(graph.keys())
while unvisited:
current_node = min(unvisited, key=lambda node: distances[node])
unvisited.remove(current_node)
for neighbor, weight in graph[current_node].items():
if neighbor in unvisited:
new_distance = distances[current_node] + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
return distances

graph = {}
n = int(input("Enter the number of edges: "))
for i in range(n):
edge = input("Enter the edge (source destination weight): ").split()
source, destination, weight = edge[0], edge[1], int(edge[2])
if source not in graph:
graph[source] = {}
graph[source][destination] = weight

source = input("Enter the source node: ")


distances = greedy_search(graph, source)
print(distances)

Enter the number of edges: 6


Enter the edge (source destination weight): A B 2
Enter the edge (source destination weight): A C 5
Enter the edge (source destination weight): B C 1
Enter the edge (source destination weight): B D 3
Enter the edge (source destination weight): C D 1
Enter the edge (source destination weight): D D 0
Enter the source node: A
{'A': 0, 'B': 2, 'C': 3, 'D': 4}

In [7]: #3
class Graph:
def __init__(self, vertices):
self.V = vertices
localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 1/7
5/5/24, 10:24 PM Assgn3

self.graph = []

def addEdge(self, u, v, w):


self.graph.append([u, v, w])

def find(self, parent, i):


if parent[i] != i:
parent[i] = self.find(parent, parent[i])
return parent[i]

def union(self, parent, rank, x, y):


if rank[x] < rank[y]:
parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x
else:
parent[y] = x
rank[x] += 1

def KruskalMST(self):
result = []
i=0
e=0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = [i for i in range(self.V)]
rank = [0] * self.V

while e < self.V - 1:


u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e += 1
result.append([u, v, w])
self.union(parent, rank, x, y)

minimumCost = 0
print("Edges in the constructed MST:")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree:", minimumCost)

if __name__ == '__main__':
vertices = int(input("Enter the number of vertices: "))
g = Graph(vertices)
edges = int(input("Enter the number of edges: "))
print("Enter the edges and their weights:")
for i in range(edges):
u, v, w = map(int, input().split())
g.addEdge(u, v, w)
g.KruskalMST()

localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 2/7
5/5/24, 10:24 PM Assgn3

Enter the number of vertices: 5


Enter the number of edges: 7
Enter the edges and their weights:
014
021
122
135
231
246
348
Edges in the constructed MST:
0 -- 2 == 1
2 -- 3 == 1
1 -- 2 == 2
2 -- 4 == 6
Minimum Spanning Tree: 10

In [8]: #4
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 printMST(self, parent):


print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])

def minKey(self, key, mstSet):


min = sys.maxsize
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index

def primMST(self):
key = [sys.maxsize] * self.V
parent = [None] * self.V
key[0] = 0
mstSet = [False] * self.V
parent[0] = -1
for cout in range(self.V):
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)

if __name__ == '__main__':
vertices = int(input("Enter the number of vertices: "))
g = Graph(vertices)
print("Enter the graph matrix:")
for i in range(vertices):
row = list(map(int, input().split()))

localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 3/7
5/5/24, 10:24 PM Assgn3

for j in range(vertices):
g.graph[i][j] = row[j]
source_vertex = int(input("Enter the source vertex: "))
g.primMST()
Enter the number of vertices: 5
Enter the graph matrix:
02060
20358
03007
68009
05790
Enter the source vertex: 0
Edge Weight
0-1 2
1-2 3
1-3 8
2-4 7

In [10]: #5
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__":
vertices = int(input("Enter the number of vertices: "))
graph = []
print("Enter the graph matrix:")
for i in range(vertices):
row = list(map(int, input().split()))
graph.append(row)
g = Graph(vertices)
localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 4/7
5/5/24, 10:24 PM Assgn3

g.graph = graph
src = int(input("Enter the source vertex: "))
g.dijkstra(src)

Enter the number of vertices: 5


Enter the graph matrix:
02400
20370
43015
07103
00530
Enter the source vertex: 0
Vertex Distance from Source
0 0
1 2
2 4
3 5
4 8

In [11]: #6
profit = []
jobs = []
deadline = []

n = int(input("Enter the number of jobs: "))


for i in range(n):
p = int(input("Enter the profit of job {}: ".format(i+1)))
profit.append(p)
j = input("Enter the name of job {}: ".format(i+1))
jobs.append(j)
d = int(input("Enter the deadline of job {}: ".format(i+1)))
deadline.append(d)

profitNJobs = list(zip(profit, jobs, deadline))


profitNJobs = sorted(profitNJobs, key=lambda x: x[0], reverse=True)

slot = [0] * (n+1)


total_profit = 0
ans = ['null'] * (n+1)

for i in range(n):
job = profitNJobs[i]
for j in range(job[2], 0, -1):
if slot[j] == 0:
ans[j] = job[1]
total_profit += job[0]
slot[j] = 1
break

print("Jobs scheduled:", ans[1:])


print("Total profit:", total_profit)

localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 5/7
5/5/24, 10:24 PM Assgn3

Enter the number of jobs: 5


Enter the profit of job 1: 200
Enter the name of job 1: j1
Enter the deadline of job 1: 3
Enter the profit of job 2: 10
Enter the name of job 2: j2
Enter the deadline of job 2: 1
Enter the profit of job 3: 15
Enter the name of job 3: j3
Enter the deadline of job 3: 2
Enter the profit of job 4: 5
Enter the name of job 4: j4
Enter the deadline of job 4: 1
Enter the profit of job 5: 30
Enter the name of job 5: j5
Enter the deadline of job 5: 3
Jobs scheduled: ['j3', 'j5', 'j1', 'null', 'null']
Total profit: 245

In [1]: import sys

def greedy_search(graph, source):


distances = {node: sys.maxsize for node in graph}
distances[source] = 0
unvisited = set(graph.keys())

while unvisited:
current_node = min(unvisited, key=lambda node: distances[node])
unvisited.remove(current_node)

for neighbor, weight in graph[current_node].items():


if neighbor in unvisited:
new_distance = distances[current_node] + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance

return distances

graph = {}
n = int(input("Enter the number of edges: "))
for i in range(n):
edge = input("Enter the edge (source destination weight): ").split()
source, destination, weight = edge[0], edge[1], int(edge[2])

if source not in graph:


graph[source] = {}
graph[source][destination] = weight

source = input("Enter the source node: ")


distances = greedy_search(graph, source)
print(distances)
Enter the number of edges: 4
Enter the edge (source destination weight): A B 4
Enter the edge (source destination weight): A C 2
Enter the edge (source destination weight): B C 5
Enter the edge (source destination weight): B D 10
Enter the source node: A
{'A': 0, 'B': 4}

localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 6/7
5/5/24, 10:24 PM Assgn3

In [ ]:

localhost:8889/nbconvert/html/LP2/Assgn3.ipynb?download=false 7/7

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