AI Lab 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Q1)

import copy

initial = [['A'], ['B', 'C'], []]


goal = ['A', 'B', 'C']
visited = []
path = []

def dfs(current, goal, visited, path):


if current in visited:
return []
state = copy.deepcopy(current)
path.append(state)
if goal in current:
return path
visited.append(state)
for i in range(3):
if current[i]:
val = current[i][-1]
current[i].pop()
for j in range(3):
if j != i:
current[j].append(val)
if dfs(current, goal, visited, path):
return path
current[j].pop()
current[i].append(val)
path.pop()
return []

dfs(initial, goal, visited, path)


for i in path:
print(*i)

Q2)

import copy

class Position:
def __init__(self, current, parent = None):
self.current = current
self.parent = parent

initial = Position([['A'], ['B', 'C'], []])


goal = ['A', 'B', 'C']

def bfs(initial, final):


q = []
v = []
q.append(initial)
v.append(copy.deepcopy(initial.current))

while q:
t = q.pop(0)
if goal in t.current:
return t
temp = copy.deepcopy(t.current)
for i in range(3):
if temp[i]:
val = temp[i][-1]
temp[i].pop()
for j in range(3):
if j != i:
temp[j].append(val)
if temp not in v:
c = copy.deepcopy(temp)
v.append(c)
q.append(Position(c, t))
temp[j].pop()
temp[i].append(val)
return False

result = bfs(initial, goal)


path = []
while result:
path.insert(0, result.current)
result = result.parent

for i in path:
print(*i)

Q5)

import heapq

class State:
def __init__(self, current, parent=None):
self.current = current
self.parent = parent

def __lt__(self, obj):


return self.current < obj.current

def __gt__(self, obj):


return self.current > obj.current

def __eq__(self, obj):


return self.current == obj.current

graph = {
"S": [("A", 1), ("B", 5), ("C", 15)],
"A": [("G", 10)],
"B": [("G", 5)],
"C": [("G", 5)],
"G": [],
}

def ucs(start: str, goal: str, graph):


pq: list[State] = []
heapq.heappush(pq, State((0, start)))
v = set()

while pq:
t = heapq.heappop(pq)
cost, curr = t.current
if curr == goal:
return t
v.add(curr)
for i, w in graph[curr]:
if i not in v:
heapq.heappush(pq, State((cost + w, i), t))

return -1

result = ucs("S", "G", graph)


path = []
while result:
path.insert(0, result.current)
result = result.parent
for i in path:
print(i[1])

You might also like