0% found this document useful (0 votes)
32 views20 pages

Ai File001

The document discusses implementing various graph search algorithms like breadth-first search, depth-first search, best-first search, A* search and their code implementation. It also discusses implementing list operations, list methods, travelling salesman problem and backward chaining in first-order logic.

Uploaded by

Aditya Kashyap
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)
32 views20 pages

Ai File001

The document discusses implementing various graph search algorithms like breadth-first search, depth-first search, best-first search, A* search and their code implementation. It also discusses implementing list operations, list methods, travelling salesman problem and backward chaining in first-order logic.

Uploaded by

Aditya Kashyap
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/ 20

1.

Write a program to implement Breadth First and Depth First


Search
CODE:-
from collections import deque

class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)

def breadth_first_search(self, start):


visited = set()
queue = deque([start])
traversal = []

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 depth_first_search(self, start):


visited = set()
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 = {}

def add_edge(self, u, v, w):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append((v, w))

def best_first_search(self, start, goal):


visited = set()
heap = [(0, start)]
while heap:
cost, node = heapq.heappop(heap)
if node not in visited:
visited.add(node)
if node == goal:
return True
for neighbor, weight in self.graph.get(node, []):
if neighbor not in visited:
heapq.heappush(heap, (weight, neighbor))
return False
def heuristic(self, node, goal):
# Simple heuristic: straight-line distance between node and goal
return abs(node[0] - goal[0]) + abs(node[1] - goal[1])

def a_star_search(self, start, goal):


open_set = set()
closed_set = set()
g_score = {start: 0}
f_score = {start: self.heuristic(start, goal)}
open_set.add(start)

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)

for neighbor, weight in self.graph.get(current, []):


if neighbor in closed_set:
continue

tentative_g_score = g_score[current] + weight

if neighbor not in open_set:


open_set.add(neighbor)
elif tentative_g_score >= g_score.get(neighbor, float('inf')):
continue

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

# Update the 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

# Print the shortest path


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)

# FIND MINIMIMUM PATH KEY


Next = key[Index].split()
# ADD TO PATH FOR OR PATH
if len(Next) == 1:

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

# implementation of traveling Salesman Problem


def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex


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

# store minimum weight Hamiltonian Cycle


min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:

# store current Path weight(cost)


current_pathweight = 0

# compute current path weight


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

# update minimum
min_path = min(min_path, current_pathweight)

return min_path
# Driver Code
if __name__ == "__main__":

# matrix representation of graph


graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
OUTPUT:-
5 .(a) Write a program to implement List operations (Nested List,
Length, Concatenation, Membership, Iteration, Indexing and Slicing)?
CODE:-
# Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Length of the list


print("Length of the nested list:", len(nested_list))

# 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")

# Iteration over a list


print("Elements of list1:")
for element in list1:
print(element)

# 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]

# Add an element at a specific index


index = 2
element = 5
my_list.insert(index, element)
print("List after adding", element, "at index", index, ":", my_list)

# Append an element to the end of the list


new_element = 6
my_list.append(new_element)
print("List after appending", new_element, ":", my_list)

# Extend the list by appending elements from another list


extension_list = [7, 8, 9]
my_list.extend(extension_list)
print("List after extending with", extension_list, ":", my_list)

# Delete an element by value


element_to_delete = 3
if element_to_delete in my_list:
my_list.remove(element_to_delete)
print("List after deleting", element_to_delete, ":", my_list)
else:
print(element_to_delete, "not found in the list")

# Delete an element by index


index_to_delete = 1
if index_to_delete < len(my_list):
del my_list[index_to_delete]
print("List after deleting element at index", index_to_delete, ":",
my_list)
else:
print("Index", index_to_delete, "out of range")
# Clear the list
my_list.clear()
print("List after clearing:", my_list)
OUTPUT:-
6. Write a program to implement First Order Predicate using:
a. Backward Chaining:
CODE:-
class KnowledgeBase:
def __init__(self):
self.facts = set()
self.rules = {}

def tell_fact(self, fact):


self.facts.add(fact)

def tell_rule(self, conclusion, premises):


if conclusion not in self.rules:
self.rules[conclusion] = []
self.rules[conclusion].append(premises)

def backward_chain(self, query):


return self.backward_chain_helper(query, set())

def backward_chain_helper(self, query, visited):


if query in self.facts:
return True
elif query in visited:
return False

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 = {}

def tell_fact(self, fact):


self.facts.add(fact)

def tell_rule(self, conclusion, premises):


if conclusion not in self.rules:
self.rules[conclusion] = []
self.rules[conclusion].append(premises)

def forward_chain(self, query):


inferred_facts = set()
agenda = [query]

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

return query in inferred_facts


# Example usage
if __name__ == "__main__":
kb = KnowledgeBase()

# 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:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy