Ad3311 - Artificial Intelligence Lab Manual
Ad3311 - Artificial Intelligence Lab Manual
INPUT:
import copy
count = 0
for i in range(n):
for j in range(n):
if ((mats[i][j]) and
(mats[i][j] != final[i][j])):
count += 1
return count
for i in range(n):
for j in range(n):
print("%d " % (mats[i][j]), end = " ")
print()
if root == None:
return
printPath(root.parent)
printMatsrix(root.mats)
print()
if isSafe(new_tile_posi[0], new_tile_posi[1]):
# Main Code
# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
123
560
784
123
506
784
123
586
704
123
586
074
Result:
Thus the program for implementing a basic search strategies for 8 puzzles was
implemented successfully.
Ex.No:1(b) Implementing a basic search strategy – 8 Queens
Date:
INPUT:
defis_safe(board, row, col, n):
# Check this row on left side
fori in range(col):
if board[row][i] == 1:
return False
return True
return False
defprint_solution(board):
for row in board:
print(" ".join('Q' if x == 1 else '.' for x in row))
defeight_queens_forward_checking():
n=8
board = [[0] * n for _ in range(n)]
ifforward_checking(board, 0, n):
print_solution(board)
else:
print("No solution exists")
eight_queens_forward_checking()
OUTPUT:
Q.......
......Q.
....Q...
.......Q
.Q......
...Q....
.....Q..
..Q.....
RESULT:
Thus the Program for implementing of basic search strategies for 8 queens problem is
implemented successfully.
Ex. No:1(c) Implementation of basic search strategy –
Date: Cryptarithmetic
INPUT:
fromitertools import permutations
defsolve_cryptarithmetic():
# Letters in the problem
letters = 'SENDMOREMONEY'
unique_letters = set(letters)
# Iterate over all permutations of digits of length equal to the number of unique letters
for perm in permutations(digits, len(unique_letters)):
# Create a mapping of letters to digits
letter_to_digit = dict(zip(unique_letters, perm))
OUTPUT:
Solution found:
SEND = 6853
MORE = 728
MONEY = 7581
RESULT:
Thus the python program for implementing a basic strategies for crptarithmetic was
successfully implemented.
Ex.No;2(a) Implementation of A* Algorithm
Date:
INPUT:
importheapq
whileopen_list:
current = heapq.heappop(open_list)[1]
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
return None
# Example usage:
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('D', 3), ('E', 5)],
'C': [('F', 2)],
'D': [('F', 1)],
'E': [('F', 2)],
'F': []
}
heuristic = {
'A': 7,
'B': 6,
'C': 2,
'D': 1,
'E': 3,
'F': 0
}
start = 'A'
goal = 'F'
path = astar(start, goal, graph, heuristic)
print("Path found:", path)
OUTPUT:
Path found: ['A', 'C', 'F']
RESULT:
Thus the python program for implementing a A* algorithm was successfully
implemented.
Ex. No.2(b) Implementation of memory bounded A* Algorithm
Date:
INPUT:
# Example usage
grid = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
start = (0, 0)
goal = (4, 4)
path = ida_star(grid, start, goal)
print("Path:", path)
OUTPUT:
Path: [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
RESULT:
Thus the python program for implementing memory bounded A* Algorithm was
Successfully implemented.
Ex.No:3 Implement Minimas algorithm for game playing
Date; (Alpha Beta Pruning)
INPUT:
# Python3 program to demonstrate
# working of Alpha-Beta Pruning
ifmaximizingPlayer:
best = MIN
return best
else:
best = MAX
return best
# Driver Code
if __name__ == "__main__":
OUTPUT:
RESULT:
Thus the python program for implement minimax algorithm for game pruning(Alpha
Beta Pruning) was successfully implemented.
Ex.No:4 Solve Constraint satisfaction problems
Date;
INPUT:
importnumpy as np
return True
ifsolve_sudoku(sudoku_grid):
print("Solved Sudoku Puzzle:")
print_grid(sudoku_grid)
else:
print("No solution exists")
OUTPUT:
Initial Sudoku Puzzle:
53..7....
6..195...
.98....6.
8...6...3
4 . . 8 .3 . . 1
7...2...6
.6....28.
...419..5
....8..79
RESULT:
Thus the python program for solving constraint Satisfaction problems was
successfully implemented.
Ex.No: 5 Implementation propositional model checking Algorithms
Date:
INPUT:
# Example moves
moves = ["right", "down", "down", "right"]
for move in moves:
new_position = move_agent(agent_position, move)
ifis_safe(new_position):
agent_position = new_position
print(f"Moved to {agent_position}, it's safe!")
else:
print(f"Move to {new_position} is not safe!")
OUTPUT:
RESULT:
Thus the python program for implementing propositional model checking algorithms
was successfully implemented.
Ex. No:6 (a) Implementation of forward chaining
Date:
INPUT:
OUTPUT:
Inferred Facts: {'D', 'C'}
RESULT:
Thus the python program of implementing forward chaining was successfully
implemented.
Ex.No:6(b) Implementation of Backward chaining
Date:
INPUT:
classKnowledgeBase:
def __init__(self):
self.rules = []
self.facts = set()
defadd_rule(self, rule):
self.rules.append(rule)
defadd_fact(self, fact):
self.facts.add(fact)
defbackward_chain(self, goal):
if goal in self.facts:
return True
for rule in self.rules:
ifrule.conclusion == goal:
if all(self.backward_chain(cond) for cond in rule.conditions):
self.facts.add(goal)
return True
return False
class Rule:
def __init__(self, conditions, conclusion):
self.conditions = conditions
self.conclusion = conclusion
# Example usage
kb = KnowledgeBase()
kb.add_fact('A')
kb.add_rule(Rule(['A'], 'B'))
kb.add_rule(Rule(['B'], 'C'))
goal = 'C'
ifkb.backward_chain(goal):
print(f"{goal} is true")
else:
print(f"{goal} is not true")
OUTPUT:
C is true
RESULT:
Thus the python program of implementing backward chaining was successfully
implemented.
Ex.No:6(c) Implementation of Resolution strategies
Date:
INPUT:
# Example usage
clause1 = {1, -2}
clause2 = {2, 3}
print(resolve(clause1, clause2))
OUTPUT:
[{1, 3}]
RESULT:
Thus the python program for implementing resolution strategies was successfully
implemented.
Ex. No:7 Build naïve Bayes models
Date:
INPUT:
importnumpy as np
import pandas as pd
fromsklearn.model_selection import train_test_split
fromsklearn.naive_bayes import GaussianNB
fromsklearn.metrics import accuracy_score
fromsklearn.datasets import load_iris
# Load dataset
data = load_iris()
X = data.data
y = data.target
# Make predictions
y_pred = model.predict(X_test)
OUTPUT:
Accuracy: 97.78%
RESULT:
Thus the python program to build naïve bayes models was successfully implemented.
INPUT:
importnumpy as np
importmatplotlib.pyplot as plt
plt.tight_layout()
plt.show()
mean_sigma = np.mean(posterior_sigma)
std_sigma = np.std(posterior_sigma)
print("Mean of sigma:", mean_sigma)
print("Standard deviation of sigma:", std_sigma)
OUTPUT:
RESULT:
Thus the python program for implementing Bayesian network and perform inferences
was successfully implemented.