Practical 6 Aim:: Name: Rohit Yadav Roll No: SCS2021103
Practical 6 Aim:: Name: Rohit Yadav Roll No: SCS2021103
Practical 6
Aim : Implement A* search algorithm for Romanian map problem.
Code:
############### ASTAR ALGORITHM ##############
nodelist = {'mumbai' : [('delhi',1200),('nasik',350),('goa', 800),
('pune',130)],
'delhi' :[('nasik', 375),('mumbai',1200)],
'nasik' :[('indore',600),('delhi',375),('mumbai',350),
('nagpur',600)],
'indore' :[('nasik',400)],
'nagpur' :[('nasik',600),('pune',450)],
'pune' :[('mumbai',130),('nagpur',450),('blore',550)],
'blore' :[('hyd', 110),('goa',750)],
'goa' :[('blore',750),('hyd',850),('mumbai',800)],
'hyd' :[('blore',110),('goa',750)]}
def goalTest(node):
return node == 'hyd'
def moveGen(node):
return nodelist[node[0]]
def sort(mylist):
for i in range(len(mylist)):
for j in range(0,len(mylist)-i-1):
if(mylist[j][1] > mylist[j+1][1]):
temp = mylist[j]
mylist[j]=mylist[j+1]
mylist[j+1]=temp
def AStar():
while(len(openList)>0):
sort(openList)
print("Open List Contains:", openList)
node = openList.pop(0)
closedList.append((node[0], hd[node[0]]))
print("Picked node:", node)
if(goalTest(node[0])):
return "Goal Found"
else:
neighbours = moveGen(node)
print("Neighbours of", node, "are:", neighbours)
for node in neighbours:
if node not in openList and node[0] not in closedList[0]:
tup = (node[0], (node[1]+ hd [node[0]]))
#tup=(delhi,1200+1515)
#print(tup)
openList.append(tup)
Code:
############ BEST FIRST SEARCH ALGORITHM ############
map_list={'Mumbai':[('Pune',750),('Delhi',1500),('Goa',1300)],
'Goa':[('Mumbai',1200)],
'Delhi':[('Mumbai',1200),('Guwahati',100),('Pune',750)],
'Chennai':['Pune',750],
'Kolkata':[('Guwahati',100),('Pune',750)],
'Pune':[('Mumbai',1200),('Kolkata',0),('Chennai',1600),
('Delhi',1500)],
'Guwahati':[('Delhi',1500),('Kolkata',0)]
}
OPEN=[[('Mumbai',1200),None]]
CLOSED=[]
def movegen(node):
return map_list[node]
def goaltest(node):
return node == 'Kolkata'
final=[]
def reconstructpath(path):
if path is None:
return ""
else:
final.append(path[0][0])
reconstructpath(path[1])
return final
def sort(a):
for i in range(len(a)):
for j in range(0,len(a)-i-1):
if(a[j][0][1]>a[j+1][0][1]):
(a[j],a[j+1])=(a[j+1],a[j])
return a
def best():
while len(OPEN)>0:
print("Open List:",OPEN)
x=sort(OPEN)
seen=x.pop(0)
N=seen[0][0]
CLOSED.append(N)
print("Closed list contains ",CLOSED)
print("Node Picked:",N)
if goaltest(N):
print(reconstructpath(seen)[::-1])
return "Found"
else:
neigh=movegen(N)
for i in neigh:
if i[0] not in CLOSED and i not in OPEN:
new=[i,seen]
OPEN.append(new)