Assiment 2
Assiment 2
import random
def DifferentPaths(tsp):
cities = list(range(len(tsp)))
solution = [0]
for i in range(len(tsp)-1):
solution.append(randomCity)
cities.remove(randomCity)
#print(solution)
return solution
LenghtOfPath = 0
for i in range(len(solution)):
LenghtOfPath += tsp[solution[i - 1]][solution[i]]
#print(LenghtOfPath)
return LenghtOfPath
def getNeighbours(solution):
neighbours = []
for i in range(1,len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
#print(neighbours)
return neighbours
bestNeighbour = neighbour
#print(bestNeighbour, bestRouteLength)
def hillClimbingAlgo(tsp):
currentSolution = DifferentPaths(tsp)
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)
currentSolution.append(0)
for i in range(len(currentSolution)):
if currentSolution[i] == 0:
currentSolution[i] = 'A'
elif currentSolution[i] == 1:
currentSolution[i] = 'B'
elif currentSolution[i] == 2:
currentSolution[i] = 'C'
elif currentSolution[i] == 3:
currentSolution[i] = 'D'
elif currentSolution[i] == 4:
currentSolution[i] = 'E'
return currentSolution
tsp = [
[13, 12, 9, 7, 0]
]
print(hillClimbingAlgo(tsp))
2. CODE FOR A*
class Graph:
def __init__(self, adjac_lis):
self.adjac_lis = adjac_lis
return self.adjac_lis[v]
# This is heuristic function which is having equal values for all nodes
H ={
'A': 1,
'B': 1,
'C': 1,
'D': 1,
'E': 1,
'G': 1
return H[n]
open_lst = set([start])
closed_lst = set([])
curr_dist_of_nodes = {}
curr_dist_of_nodes[start] = 0
adjac_nodes = {}
adjac_nodes[start] = start
while len(open_lst) > 0:
n = None
for v in open_lst:
if n == None or curr_dist_of_nodes[v] + self.h(v) < curr_dist_of_nodes[n] + self.h(n):
n = v;
if n == None:
return None
if n == stop:
reconst_path = []
while adjac_nodes[n] != n:
reconst_path.append(n)
n = adjac_nodes[n]
reconst_path.append(start)
reconst_path.reverse()
open_lst.add(m)
adjac_nodes[m] = n
else:
adjac_nodes[m] = n
if m in closed_lst:
closed_lst.remove(m)
open_lst.add(m)
open_lst.remove(n)
closed_lst.add(n)
return None
adjac_lis = {
'A': [('B', 2), ('E', 3)],
'B': [('A', 2),('C',1),('G',9)],
'E': [('A',3),('D',6)],
'G': [('D',1),('B',9)]
}
graph1 = Graph(adjac_lis)