Professional Documents
Culture Documents
Ai File001
Ai File001
class Graph:
def __init__(self):
self.graph = {}
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
traversal.append(node)
for neighbor in self.graph.get(node, []):
if neighbor not in visited:
queue.append(neighbor)
return traversal
def dfs_util(node):
visited.add(node)
traversal.append(node)
for neighbor in self.graph.get(node, []):
if neighbor not in visited:
dfs_util(neighbor)
dfs_util(start)
return traversal
# Example usage
if __name__ == "__main__":
graph = Graph()
graph.add_edge('A', 'B')
graph.add_edge('A', 'C')
graph.add_edge('B', 'D')
graph.add_edge('B', 'E')
graph.add_edge('C', 'F')
print("Breadth-First Search:")
print(graph.breadth_first_search('A'))
print("\nDepth-First Search:")
print(graph.depth_first_search('A'))
OUTPUT:-
2.Write a Program for the Best First Search and A* search algorithm
CODE:-
import heapq
class Graph:
def __init__(self):
self.graph = {}
while open_set:
current = min(open_set, key=lambda x: f_score[x])
if current == goal:
return True
open_set.remove(current)
closed_set.add(current)
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score +
self.heuristic(neighbor, goal)
return False
# Example usage
if __name__ == "__main__":
graph = Graph()
graph.add_edge((0, 0), (1, 0), 1)
graph.add_edge((0, 0), (0, 1), 1)
graph.add_edge((1, 0), (1, 1), 1)
graph.add_edge((1, 1), (2, 1), 1)
graph.add_edge((0, 1), (0, 2), 1)
graph.add_edge((0, 2), (1, 2), 1)
graph.add_edge((1, 2), (2, 2), 1)
start_node = (0, 0)
goal_node = (2, 2)
print("Best-First Search:")
print(graph.best_first_search(start_node, goal_node))
print("\nA* Search:")
print(graph.a_star_search(start_node, goal_node))
OUTPUT:-
3. Write a program to implement AO* algorithm
CODE:-
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
Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost,
H)
# ADD TO PATH FOR AND PATH
else:
Path +='<--('+key[Index]+') '
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
weight = 1
# Updated cost
print('Updated Cost :')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))
OUTPUT:-
4. Write a program to implement Travelling Salesman Problem
CODE:-
# Python3 program to implement traveling salesman
# problem using naive approach.
from sys import maxsize
from itertools import permutations
V=4
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
# Concatenation of lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print("Concatenated list:", concatenated_list)
# Membership check
if 2 in list1:
print("2 is present in list1")
else:
print("2 is not present in list1")
# Indexing
print("Element at index 0 in list1:", list1[0])
# Slicing
print("Sliced list1 from index 1 to 2:", list1[1:3])
OUTPUT:-
5. (b) Write a program to implement List methods (Add, Append, and
Extend & Delete).
CODE:-
# Define a list
my_list = [1, 2, 3, 4]
visited.add(query)
if query in self.rules:
for premises in self.rules[query]:
if all(self.backward_chain_helper(p, visited) for p in premises):
return True
return False
# Example usage
if __name__ == "__main__":
kb = KnowledgeBase()
# Define facts
kb.tell_fact("Human(John)")
kb.tell_fact("Human(Mary)")
kb.tell_fact("Mortal(John)")
kb.tell_fact("Mortal(Mary)")
# Define rules
kb.tell_rule("Mortal(X)", ["Human(X)"])
# Query
print("Is John mortal?", kb.backward_chain("Mortal(John)"))
print("Is Mary mortal?", kb.backward_chain("Mortal(Mary)"))
print("Is Socrates mortal?", kb.backward_chain("Mortal(Socrates)"))
OUTPUT:-
6. Write a program to implement First Order Predicate using:
b. Forward Chaining:
CODE:-
class KnowledgeBase:
def __init__(self):
self.facts = set()
self.rules = {}
while agenda:
current_fact = agenda.pop(0)
if current_fact in self.facts:
inferred_facts.add(current_fact)
if current_fact in self.rules:
for rule_premises in self.rules[current_fact]:
if all(p in inferred_facts for p in rule_premises):
inferred_facts.add(current_fact)
agenda.append(current_fact)
break
# Define facts
kb.tell_fact("Human(John)")
kb.tell_fact("Human(Mary)")
# Define rules
kb.tell_rule("Mortal(X)", ["Human(X)"])
# Query
print("Is John mortal?", kb.forward_chain("Mortal(John)"))
print("Is Mary mortal?", kb.forward_chain("Mortal(Mary)"))
print("Is Socrates mortal?",
kb.forward_chain("Mortal(Socrates)"))
OUTPUT:-