0% found this document useful (0 votes)
58 views14 pages

Ahsanullah University of Science and Technology (AUST)

The document describes Python code that implements greedy best-first search and A* search algorithms in a modular and interactive way. It defines classes for GBFS and A* graphs that contain the search algorithms as methods, allow inputting of graph data, and provide options to clear, display, and save the database. The algorithms find the shortest path between start and goal nodes using a priority queue.

Uploaded by

Ashna Ahmed
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)
58 views14 pages

Ahsanullah University of Science and Technology (AUST)

The document describes Python code that implements greedy best-first search and A* search algorithms in a modular and interactive way. It defines classes for GBFS and A* graphs that contain the search algorithms as methods, allow inputting of graph data, and provide options to clear, display, and save the database. The algorithms find the shortest path between start and goal nodes using a priority queue.

Uploaded by

Ashna Ahmed
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/ 14

Ahsanullah University of Science and Technology (AUST)

Department of Computer Science and Engineering

ASSIGNMENT #03
Course No.: CSE4108
Course Title: Artificial Intelligence Lab

Date of Submission: 25-08-2020

Submitted By-
Ashna Nawar Ahmed
I.D.: 16.02.04.024
Section-A1
Year- 4th
Semester-1st
Department-CSE
Question 1: Write a Python program that reads the file created as demonstrated into a
dictionary taking ‘name’ as the key and a list consisting of ‘dept’ and ‘cgpa’ as the value for
each line. Make changes in some ‘cgpa’ and then write back the whole file.
Description:
Here input(name, department, CGPA) is saved into student_data file, then it is read into the dictionary
student_dict. Afterwards, CGPA of a student is changed and then the file is written into
student_data_new.txt file.

Python Code:
f1=open("student_data.txt", "w")

print("\n")

student_num=int(input("Enter number of students:"))

for i in range(student_num):

name=str(input("Enter the name:"))

dept=str(input("Enter the department:"))

cgpa=str(input("Enter the cgpa:"))

std=name+"\t"+dept+"\t"+cgpa+"\n"

#print(std, end="\n", file=f1)

f1.write(std)

print("\n")

f1.close

student_dict={}

f1=open("student_data.txt", "r")

for l in f1:

name, dept, cgpa =l.split("\t")

cgpa=cgpa.split("\n")

student_dict[name]=[dept,cgpa[0]]

f1.close

print("Original Data:\n{Name:[Dept, CGPA]}")

print(student_dict)
std_name=input("Which student's cgpa do you want to change?")

std_cgpa=input("Input new cgpa:")

student_dict[std_name]=[(student_dict.get(name))[0],std_cgpa]

print("\nNew Data:\n{Name:[Dept, CGPA]}")

print(student_dict)

f2=open("student_data_new.txt", "w")

for i in student_dict:

name=str(i)

dept=str(student_dict[i][0])

cgpa=str(student_dict[i][1])

std=name+"\t"+dept+"\t"+cgpa+"\n"

#print(std)

#print(std, end="\n", file=f2)

f2.write(std)

f2.close
Screenshot:

Question 2(a): Implement in generic ways (as multi-modular and interactive systems) the
Greedy Best-First search algorithm in Prolog or in Python.
Description:
Here, Greedy Best First Search algorithm has been implemented in a multi-modular and interactive
format. The GBFS_Graph class has been implemented in such a way that it contains the algorithm
implementation itself as well as the method for inputting data. The provision for clearing and displaying
database has also been provided.
Python Code:
from queue import PriorityQueue

class GBFS_Graph:

def __init__(self):

self.graph = []

self.nodeDictionary = {}

self.path = []

def display(self):

print("Shortest path is: ")

for x in range(len(self.path)):

print(self.path[x]+1, end = ' ')

def greedyBestFirstSearch(self, s_node, g_node):

pq = PriorityQueue()

while s_node != g_node:

if pq.empty():

pq.put((0, [s_node]))

else:

currLeast = pq.get()

currLeastPriority = currLeast[0]

s_node = currLeast[1][len(currLeast[1]) - 1]

links = self.graph[s_node]

if len(links) != 0:

for items in links:

newList = []
newPriority = 0

newList.extend(currLeast[1])

newList.append(items[0])

newPriority = self.nodeDictionary[items[0]]

if items[0] == g_node:

s_node = g_node

currLeast[1].append(g_node)

print(currLeast[1])

self.path = currLeast[1]

break

pq.put((newPriority, newList))

def inputData(self):

print("Enter the number of nodes: ")

totalNodes = int(input())

self.graph = [[] for t in range(totalNodes)]

for i in range(totalNodes):

print("Enter the node: ")

nodeNumber = int(input())

print("Enter the value of heuristic function: ")

h_Function = int(input())

self.nodeDictionary[nodeNumber-1] = h_Function

print("Enter the number of edges: ")

totalEdges = int(input())

for i in range(totalEdges):

print("Enter source Node: ")

srcNode = int(input())
print("Enter destination node: ")

destNode = int(input())

print("Enter cost: ")

cost = int(input())

self.graph[srcNode - 1].append((destNode - 1, cost))

g = GBFS_Graph()

print("GBFS search algorithm:")

run=True

while(run):

print("\nEnter a choice(1-5):")

print("1: Clear Database")

print("2: Execute Greedy Best First Search")

print("3: Display Database")

print("4: Save Database")

print("5: Exit")

choice=int(input())

if choice==1:

print("Clearing current database.")

g.graph = []

g.nodeDictionary = {}

g.path = []
print("Database cleared.")

elif choice==2:

g.inputData()

print("Enter Source node: ")

srcNode = int(input())

print("Enter Goal node: ")

goal = int(input())

g.greedyBestFirstSearch(srcNode - 1, goal - 1)

g.display()

elif choice==3:

print("Current Database:\nCurrent Graph(heuristic function, node):")

print(g.graph)

elif choice==4:

print("Saving current database state...")

f1=open("node_db_astar.txt", "w")

f1.write(str(g.graph))

f1.write("\n")

f1.write(str(g.nodeDictionary))

f1.close

print("Saved.")

else:

run=False
Screenshot:

Question 2(b): Implement in generic ways (as multi-modular and interactive systems) the
A*(star) search algorithm in Prolog or in Python.
Description:
Here, A* Search algorithm has been implemented in a multi-modular and interactive format. The
astar_Graph class has been implemented in such a way that it contains the algorithm implementation
itself as well as the method for inputting data. The provision for clearing and displaying database has
also been provided.
Python Code:
from queue import PriorityQueue

class astar_Graph:

def __init__(self):

self.graph = []

self.nodeDictionary = {}

self.path = []

def display(self):

print("Shortest path is: ")

for x in range(len(self.path)):

print(self.path[x]+1, end = ' ')

def aStarSearch(self, s_node, g_node):

pq = PriorityQueue()

while s_node != g_node:

if pq.empty():

pq.put((0, [s_node]))

else:

currLeast = pq.get()

currLeastPriority = currLeast[0]

s_node = currLeast[1][len(currLeast[1]) - 1]

links = self.graph[s_node]

if len(links) != 0:

for items in links:

newList = []

newPriority = 0
newList.extend(currLeast[1])

newList.append(items[0])

if len(newList) > 1:

for i in range(len(newList) - 1):

for j in self.graph[newList[i]]:

if j[0] == newList[i+1]:

newPriority += j[1]

newPriority = newPriority + self.nodeDictionary[items[0]]

if items[0] == g_node:

s_node = g_node

currLeast[1].append(g_node)

print(currLeast[1])

self.path = currLeast[1]

break

pq.put((newPriority, newList))

def inputData(self):

print("Enter the number of nodes: ")

totalNodes = int(input())

self.graph = [[] for t in range(totalNodes)]

for i in range(totalNodes):

print("Enter the node: ")

nodeNumber = int(input())

print("Enter the value of heuristic function: ")

h_Function = int(input())

self.nodeDictionary[nodeNumber-1] = h_Function

print("Enter the number of edges: ")

totalEdges = int(input())
for i in range(totalEdges):

print("Enter source Node: ")

srcNode = int(input())

print("Enter destination node: ")

destNode = int(input())

print("Enter cost: ")

cost = int(input())

self.graph[srcNode - 1].append((destNode - 1, cost))

g = astar_Graph()

print("A Star search algorithm:")

run=True

while(run):

print("\nEnter a choice(1-5):")

print("1: Clear Database")

print("2: Execute A Star Search")

print("3: Display Database")

print("4: Save Database")

print("5: Exit")

choice=int(input())

if choice==1:

print("Clearing current database.")


g.graph = []

g.nodeDictionary = {}

g.path = []

print("Database cleared.")

elif choice==2:

g.inputData()

print("Enter Source node: ")

srcNode = int(input())

print("Enter Goal node: ")

goal = int(input())

g.aStarSearch(srcNode - 1, goal - 1)

g.display()

elif choice==3:

print("Current Database:\nCurrent Graph(heuristic function, node):")

print(g.graph)

elif choice==4:

print("Saving current database state...")

f1=open("node_db_astar.txt", "w")

f1.write(str(g.graph))

f1.write("\n")

f1.write(str(g.nodeDictionary))

f1.close

print("Saved.")

else:

run=False
Screenshot:

You might also like