0% found this document useful (0 votes)
16 views13 pages

Ai File

The document contains multiple programming tasks related to graph algorithms, including implementations of Breadth First Search, Depth First Search, Best First Search, A* search, AO* algorithm, and Travelling Salesman Problem. It also includes operations on lists and first-order predicate logic using backward and forward chaining. Each section provides code snippets and expected outputs for the respective algorithms and operations.

Uploaded by

shashank4230g
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)
16 views13 pages

Ai File

The document contains multiple programming tasks related to graph algorithms, including implementations of Breadth First Search, Depth First Search, Best First Search, A* search, AO* algorithm, and Travelling Salesman Problem. It also includes operations on lists and first-order predicate logic using backward and forward chaining. Each section provides code snippets and expected outputs for the respective algorithms and operations.

Uploaded by

shashank4230g
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/ 13

SHASHANK

Q1.Write a program to implement Breadth First and Depth First Search

from collections import defaultdict

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def bfs(self, start):


visited = [False] * (len(self.graph))
queue = []
queue.append(start)
visited[start] = True

while queue:
start = queue.pop(0)
print(start, end=" ")

for i in self.graph[start]:
if not visited[i]:
queue.append(i)
visited[i] = True

def dfs_util(self, v, visited):


visited[v] = True
print(v, end=" ")

for i in self.graph[v]:
if not visited[i]:
self.dfs_util(i, visited)

def dfs(self, start):


visited = [False] * (len(self.graph))
self.dfs_util(start, visited)

g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)

print("Breadth First Search (BFS):")


35316702022

1
SHASHANK

g.bfs(2)
print("\nDepth First Search (DFS):")
g.dfs(2)

OUTPUT

35316702022

2
SHASHANK

Q2.Write a Program for the Best First Search and A* search algorithm

from queue import PriorityQueue


v = 14
graph = [[] for i in range(v)]

def best_first_search(actual_Src, target, n):


visited = [False] * n
pq = PriorityQueue()
pq.put((0, actual_Src))
visited[actual_Src] = True

while pq.empty() == False:


u = pq.get()[1]
# Displaying the path having lowest cost
print(u, end=" ")
if u == target:
break

for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()

def addedge(x, y, cost):


graph[x].append((y, cost))
graph[y].append((x, cost))

addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)
addedge(1, 4, 9)
addedge(1, 5, 8)
addedge(2, 6, 12)
addedge(2, 7, 14)
addedge(3, 8, 7)
addedge(8, 9, 5)
addedge(8, 10, 6)
addedge(9, 11, 1)
addedge(9, 12, 10)
addedge(9, 13, 2)

35316702022

3
SHASHANK

source = 0
target = 9
best_first_search(source, target, v)

OUTPUT

35316702022

4
SHASHANK

Q5.Write a program to implement AO* algorithm?

def Cost(H, condition, weight = 1):


cost = {}
if 'AND' in condition:
AND_nodes = condition['AND']
Path_A = ' AND '.join(AND_nodes)
PathA = sum(H[node]+weight for node in AND_nodes)
cost[Path_A] = PathA

if 'OR' in condition:
OR_nodes = condition['OR']
Path_B =' OR '.join(OR_nodes)
PathB = min(H[node]+weight for node in OR_nodes)
cost[Path_B] = PathB
return cost

def update_cost(H, Conditions, weight=1):


Main_nodes = list(Conditions.keys())
Main_nodes.reverse()
least_cost= {}
for key in Main_nodes:
condition = Conditions[key]
print(key,':', Conditions[key],'>>>', Cost(H, condition, weight))
c = Cost(H, condition, weight)
H[key] = min(c.values())
least_cost[key] = Cost(H, condition, weight)
return least_cost

def shortest_path(Start,Updated_cost, H):


Path = Start
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_cost)

Next = key[Index].split()
if len(Next) == 1:

Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost, H)
else:
Path +='<--('+key[Index]+') '

35316702022

5
SHASHANK

Start = Next[0]
Path += '[' +shortest_path(Start, Updated_cost, H) + ' + '

Start = Next[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'

return Path

H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}

Conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}

weight = 1

print('Updated Cost :')


Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))

OUTPUT

35316702022

6
SHASHANK

Q7.Write a program to implement Travelling Salesman Problem.

from sys import maxsize


from itertools import permutations
V=4

def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex


vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:

current_pathweight = 0

k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]

min_path = min(min_path, current_pathweight)

return min_path

if __name__ == "__main__":

graph = [[0, 10, 15, 20], [10, 0, 35, 25],


[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))

OUTPUT

35316702022

7
SHASHANK

Q8(a) Write a program to implement List operations (Nested List, Length, Concatenation,
Membership, Iteration, Indexing and Slicing)? (b) Write a program to implement List methods
(Add, Append, and Extend & Delete).

(A)=

list1 = [1, 2, 3, 4, 5]

list2 = [[1, 2, 3], [4, 5, 6]]

print(len(list1))

list3 = list1 + list2

print(list3)

print(4 in list1)

for i in list1:
print(i)

print(list1[2])

print(list1[2:4])

OUTPUT

35316702022

8
SHASHANK

(B)=
list1 = [1, 2, 3, 4, 5]

list1.append(6)
print(list1)

list1.append([7, 8, 9])
print(list1)

list1.extend([10, 11, 12])


print(list1)

list1.remove(6)
print(list1)

list1.remove([7, 8, 9])
print(list1)

OUTPUT

35316702022

9
SHASHANK

Q9 Write a program to implement First Order Predicate using: a. Backward Chaining b.


Forward Chaining .

knowledge_base = {
'parent': [('shashank', 'haardeek'), ('haardeek', 'rohan')],
'grandparent': [('?', '?')], # Placeholder for inferred knowledge
}

def backward_chaining(goal_predicate, goal_arguments):


if goal_predicate in knowledge_base:

for fact in knowledge_base[goal_predicate]:


if match_arguments(goal_arguments, fact[0]):
return True
for rule in knowledge_base[goal_predicate]:
if backward_chaining(rule[1], goal_arguments):
inferred_arguments = unify_arguments(rule[0], goal_arguments)
knowledge_base[goal_predicate].append(inferred_arguments)
return True
return False

def match_arguments(arguments1, arguments2):


if arguments1 == arguments2:
return True
elif arguments1 == '?' or arguments2 == '?':
return True
else:
return False

def unify_arguments(arguments1, arguments2):


if arguments1 == '?' or arguments2 == '?':
return arguments2
else:
return arguments1

goal_predicate = 'grandparent'
goal_arguments = ('shashank', 'rohan')

result = backward_chaining(goal_predicate, goal_arguments)

if result:
print(f"Yes, {goal_arguments[0]} is a {goal_predicate} of {goal_arguments[1]}.")
else:
print(f"No, {goal_arguments[0]} is not a {goal_predicate} of {goal_arguments[1]}.")

35316702022

10
SHASHANK

OUTPUT

(B)-class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []

def add_fact(self, fact):


self.facts.append(fact)

def add_rule(self, antecedents, consequent):


self.rules.append((antecedents, consequent))

def forward_chaining(self, query):


inferred = set()

while True:
new_inferred = set()

for rule in self.rules:


antecedents, consequent = rule
if all(fact in inferred for fact in antecedents) and consequent not in inferred:
new_inferred.add(consequent)

if not new_inferred:
break

inferred |= new_inferred

return query in inferred

kb = KnowledgeBase()

kb.add_fact("Parent(john, Mary)")
kb.add_fact("Parent(Mary, Bob)")
kb.add_fact("Parent(Mary, Alice)")

kb.add_rule(["Parent(x, y)"], "Grandparent(x, z)")

query = "Grandparent(John, Bob)"


result = kb.forward_chaining(query)

if result:
35316702022

11
SHASHANK

print(f"The statement '{query}' is inferred from the knowledge base.")


else:
print(f"The statement '{query}' is not inferred from the knowledge base.")

OUTPUT

35316702022

12
SHASHANK

35316702022

13

You might also like