Index AI
Index AI
Index AI
a. Backward Chaining
b. Forward Chaining
10. Write a program for Text Classification for the given sentence using
NLTK
PRACTICAL 1
Write a program to implement Breadth First and
Depth First Search.
SOURCE CODE
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
print("BFS Traversal:")
g.bfs(2)
print("\nDFS Traversal:")
g.dfs(2)
OUTPUT
PRACTICAL 2
Write a program to implement Water Jug Problem.
SOURCE CODE
# Function to find all possible states for pouring water from one jug to
another
def pour(jug1, jug2, capacities):
max1, max2 = capacities
states = []
return states
while queue:
current_state = queue.popleft()
if current_state == target:
return True
visited.add(current_state)
jug1, jug2 = current_state
OUTPUT
PRACTICAL 3
Write a Program A* search algorithm
SOURCE CODE
import heapq
class Node:
def __init__(self, state, parent=None, action=None, g=0, h=0):
self.state = state
self.parent = parent
self.action = action
self.g = g # cost from start node to current node
self.h = h # heuristic cost from current node to goal node
def f(self):
return self.g + self.h
def astar_search(initial_state, goal_state, heuristic):
open_list = []
closed_list = set()
start_node = Node(initial_state)
start_node.h = heuristic(initial_state, goal_state)
OUTPUT
PRACTICAL 4
Write a program to implement AO* algorithm
SOURCE CODE
# Cost to find the AND and OR path
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
PRACTICAL 5
Write a program to implement 4-Queen Problem
SOURCE CODE
def is_safe(board, row, col):
# Check if there is a queen in the same row to the left
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on the left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on the left side
for i, j in zip(range(row, len(board)), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_queen_problem(board, col):
# Base case: if all queens are placed
if col >= len(board):
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve_queen_problem(board, col + 1):
return True
board[i][col] = 0
return False
def print_solution(board):
for row in board:
print(row)
def four_queen_problem():
# Initialize 4x4 chessboard
board = [[0] * 4 for _ in range(4)]
if not solve_queen_problem(board, 0):
print("Solution does not exist")
return False
print_solution(board)
return True
# Solve and print solution for 4-Queen Problem
four_queen_problem()
OUTPUT
PRACTICAL 6
Write a program to implement hill climbing &
steepest ascent hill climbing algorithm.
for _ in range(max_iterations):
neighbors = problem.neighbors(current_state)
next_state = max(neighbors, key=lambda state:
problem.heuristic(state))
return current_state
class Problem:
def initial_state(self):
return random.randint(1, 100)
# Example usage
problem = Problem()
solution = hill_climbing(problem, 100)
print("Solution found by Hill Climbing:", solution)
print("Heuristic value at solution state:", problem.heuristic(solution))
OUTPUT
SOURCE CODE OF STEEPEST ASCENT HILL CLIMBING
import random
for _ in range(max_iterations):
neighbors = problem.neighbors(current_state)
best_neighbor = max(neighbors, key=lambda state:
problem.heuristic(state))
if problem.heuristic(best_neighbor) <=
problem.heuristic(current_state):
return current_state
current_state = best_neighbor
return current_state
class Problem:
def initial_state(self):
return random.randint(1, 100)
# Example usage
problem = Problem()
solution = steepest_ascent_hill_climbing(problem, 100)
print("Solution found by Steepest Ascent Hill Climbing:", solution)
print("Heuristic value at solution state:", problem.heuristic(solution))
OUTPUT
PRACTICAL 7
Write a program to implement Travelling Salesman
Problem.
SOURCE CODE
import itertools
def calculate_distance(points):
# Calculate the total distance between points in the given order
total_distance = 0
num_points = len(points)
for i in range(num_points):
total_distance += distance(points[i], points[(i + 1) % num_points])
return total_distance
def brute_force_tsp(points):
# Generate all possible permutations of the points
all_permutations = itertools.permutations(points)
min_distance = float('inf')
best_route = None
# Iterate over all permutations and find the one with the minimum
distance
for permutation in all_permutations:
current_distance = calculate_distance(permutation)
if current_distance < min_distance:
min_distance = current_distance
best_route = permutation
# Example usage
points = [(0, 0), (1, 2), (3, 1), (2, 3)]
best_route, min_distance = brute_force_tsp(points)
print("Best route:", best_route)
print("Minimum distance:", min_distance)
OUTPUT
PRACTICAL 8
(a)Write a program to implement List
operations (Nested List,Length,
Concatenation, Membership, Iteration,
Indexing and Slicing)?
SOURCE CODE
# Nested List
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Length of a 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 Test
print("Is 2 present in list1?", 2 in list1)
# Indexing
print("Element at index 1 of list2:", list2[1])
# Slicing
print("Sliced elements from index 1 to 3 of list2:", list2[1:3])
OUTPUT
(b) Write a program to implement List
methods (Add, A end, and Extend &
Delete).
SOURCE CODE
# Nested List
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Length of a 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 Test
print("Is 2 present in list1?", 2 in list1)
# Indexing
print("Element at index 1 of list2:", list2[1])
# Slicing
print("Sliced elements from index 1 to 3 of list2:", list2[1:3])
OUTPUT
PRACTICAL 9
(a)Write a program to implement First
Order Predicate using Backward
Chaining .
SOURCE CODE
class Predicate:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments
def __str__(self):
return f"{self.name}({', '.join(self.arguments)})"
class Rule:
def __init__(self, head, body):
self.head = head
self.body = body
def __str__(self):
return f"{self.head} :- {' ,'.join([str(p) for p in self.body])}"
class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []
# Example usage
if __name__ == "__main__":
# Creating a knowledge base
kb = KnowledgeBase()
# Backward Chaining
if backward_chaining(kb, goal):
print(f"{goal} is true.")
else:
print(f"{goal} is false.")
OUTPUT
(b)Write a program to implement First
Order Predicate using Forward
Chaining .
SOURCE CODE
class Predicate:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments
def __str__(self):
return f"{self.name}({', '.join(self.arguments)})"
class Rule:
def __init__(self, head, body):
self.head = head
self.body = body
def __str__(self):
return f"{self.head} :- {' ,'.join([str(p) for p in self.body])}"
class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []
# Example usage
if __name__ == "__main__":
# Creating a knowledge base
kb = KnowledgeBase()
# Forward Chaining
if forward_chaining(kb, goal):
print(f"{goal} is true.")
else:
print(f"{goal} is false.")
OUTPUT
PRACTICAL 10
Write a program for Text Classification for the given
sentence using NLTK.
SOURCE CODE
import nltk
from nltk.corpus import movie_reviews
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy
# Prepare data
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
def document_features(document):
document_words = set(document)
features = {}
for word in word_features:
features[word] = (word in document_words)
return features
# Extract features and split data into training and testing sets
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[100:], featuresets[:100]
# Example usage
review = "This movie was great!"
words = word_tokenize(review)
features = document_features(words)
print("Predicted label:", classifier.classify(features))
SOURCE CODE