AI Lab
AI Lab
BFS
from collections import defaultdict
# Constructor
def __init__(self):
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print(s, end=" ")
# Driver code
if __name__ == '__main__':
2. DFS
# Python3 program to print DFS traversal
# from a given graph
from collections import defaultdict
# Constructor
def __init__(self):
# Driver's code
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
Output:
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
for i in range(n_iterations):
# Decrease temperature
t = temp / float(i + 1)
# Generate candidate solution
candidate = get_neighbor(current, step_size)
candidate_eval = objective(candidate)
# Check if we should keep the new solution
if candidate_eval < best_eval or random.random() <
math.exp((current_eval - candidate_eval) / t):
current, current_eval = candidate, candidate_eval
if candidate_eval < best_eval:
best, best_eval = candidate, candidate_eval
scores.append(best_eval)
5. Wumpus Problem
class Agent:
def __init__(self):
self.__wumpusWorld = [
['','','P',''], # Rooms [1,1] to [4,1]
['','','',''], # Rooms [1,2] to [4,2]
['W','','',''], # Rooms [1,3] to [4,3]
['','','',''], # Rooms [1,4] to [4,4]
] # This is the wumpus world shown in the assignment question.
# A different instance of the wumpus world will be used for
evaluation.
self.__curLoc = [1,1]
self.__isAlive = True
self.__hasExited = False
def __FindIndicesForLocation(self,loc):
x,y = loc
i,j = y-1, x-1
return i,j
def __CheckForPitWumpus(self):
ww = self.__wumpusWorld
i,j = self.__FindIndicesForLocation(self.__curLoc)
if 'P' in ww[i][j] or 'W' in ww[i][j]:
print(ww[i][j])
self.__isAlive = False
print('Agent is DEAD.')
return self.__isAlive
index = validActions.index(action)
validMoves = [[0,1],[0,-1],[-1,0],[1,0]]
move = validMoves[index]
newLoc = []
for v, inc in zip(self.__curLoc,move):
z = v + inc #increment location index
z = 4 if z>4 else 1 if z<1 else z #Ensure that index is between 1
and 4
newLoc.append(z)
self.__curLoc = newLoc
print('Action Taken: {0}, Current Location
{1}'.format(action,self.__curLoc))
if self.__curLoc[0]==4 and self.__curLoc[1]==4:
self.__hasExited=True
return self.__CheckForPitWumpus()
def __FindAdjacentRooms(self):
cLoc = self.__curLoc
validMoves = [[0,1],[0,-1],[-1,0],[1,0]]
adjRooms = []
for vM in validMoves:
room = []
valid = True
for v, inc in zip(cLoc,vM):
z = v + inc
if z<1 or z>4:
valid = False
break
else:
room.append(z)
if valid==True:
adjRooms.append(room)
return adjRooms
adjRooms = self.__FindAdjacentRooms()
for room in adjRooms:
i,j = self.__FindIndicesForLocation(room)
if 'P' in ww[i][j]:
breeze = True
if 'W' in ww[i][j]:
stench = True
return [breeze,stench]
def FindCurrentLocation(self):
return self.__curLoc
def main():
ag = Agent()
print('curLoc',ag.FindCurrentLocation())
print('Percept [breeze, stench] :',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
if __name__=='__main__':
main()
6. 8 puzzle Problem
# Python code to display the way from the root
# node to the final destination node for N*N-1 puzzle
# algorithm by the help of Branch and Bound technique
# The answer assumes that the instance of the
# puzzle can be solved
count = 0
for i in range(n):
for j in range(n):
if ((mats[i][j]) and
(mats[i][j] != final[i][j])):
count += 1
return count
for i in range(n):
for j in range(n):
print("%d " % (mats[i][j]), end = " ")
print()
# Printing the path from the root node to the final node
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatsrix(root.mats)
print()
if isSafe(new_tile_posi[0], new_tile_posi[1]):
# Main Code
# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
def GetDistance(self):
pass
def CreateChildren(self):
pass
# Creating subclass
class State_String(State):
def __init__(self, value, parent, start=0, goal=0):
super(State_String, self).__init__(value, parent, start, goal)
self.dist = self.GetDistance()
def GetDistance(self):
if self.value == self.goal:
return 0
dist = 0
for i in range(len(self.goal)):
letter = self.goal[i]
if letter in self.value:
dist += abs(i - self.value.index(letter))
else:
dist += len(self.goal) # Penalty if letter is not in the string
return dist
def CreateChildren(self):
if not self.children:
for i in range(len(self.value) - 1):
val = list(self.value)
# Swap adjacent letters
val[i], val[i + 1] = val[i + 1], val[i]
child = State_String("".join(val), self)
self.children.append(child)
def Solve(self):
startState = State_String(self.start, None, self.start, self.goal)
count = 0
self.priorityQueue.put((0, count, startState))
if not self.path:
print("Goal is not possible: " + self.goal)
return self.path
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i], neighbour[j] = neighbour[j], neighbour[i] # Swap two cities
neighbours.append(neighbour)
return neighbours
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
while True:
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp,
neighbours)
if __name__ == "__main__":
main()
10.
def greet(bot_name, birth_year):
print("Hello! My name is {0}.".format(bot_name))
print("I was created in {0}.".format(birth_year))
def remind_name():
print('Please, remind me your name.')
name = input()
print("What a great name you have, {0}!".format(name))
def provide_information():
while True:
print("What information would you like to know?")
print("1. Courses offered this semester")
print("2. Next campus event")
print("3. How to apply for financial aid")
print("4. College facilities")
print("5. Student organizations")
if choice == 1:
print("This semester, we offer the following courses:")
print("- Mathematics 101")
print("- Introduction to Computer Science")
print("- English Literature")
print("- Biology 101")
print("- History of Art")
elif choice == 2:
print("The next campus event is the career fair on March 15th from 10
AM to 4 PM in the Student Center.")
elif choice == 3:
print("To apply for financial aid, visit the Financial Aid Office or check our
website for scholarship opportunities.")
elif choice == 4:
print("Our college has the following facilities:")
print("- Library")
print("- Gymnasium")
print("- Student Lounge")
print("- Computer Lab")
print("- Cafeteria")
elif choice == 5:
print("Here are some popular student organizations:")
print("- Coding Club")
print("- Art Society")
print("- Debate Team")
print("- Environmental Club")
else:
print("I’m sorry, I didn’t understand that.")