0% found this document useful (0 votes)
19 views33 pages

Ad3311 - Artificial Intelligence Laboratory-6-38

The document outlines the implementation of various algorithms using Python, including the 8-Queens problem, A* and memory-bounded A* for the 8-puzzle problem, Minimax for Tic-Tac-Toe, and a Constraint Satisfaction Problem for Sudoku. Each section provides an aim, algorithm steps, and sample code demonstrating the successful execution of the respective algorithm. The results confirm that all implementations were executed successfully.

Uploaded by

examcell.vvcet
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)
19 views33 pages

Ad3311 - Artificial Intelligence Laboratory-6-38

The document outlines the implementation of various algorithms using Python, including the 8-Queens problem, A* and memory-bounded A* for the 8-puzzle problem, Minimax for Tic-Tac-Toe, and a Constraint Satisfaction Problem for Sudoku. Each section provides an aim, algorithm steps, and sample code demonstrating the successful execution of the respective algorithm. The results confirm that all implementations were executed successfully.

Uploaded by

examcell.vvcet
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/ 33

1

1 Implement basic search strategies for 8 - Queens problem Date:

Aim:
To implement the basic search strategies for solving 8 - Queens problem using Python
Programming.

Algorithm:
Step 1: This pseudocode uses a backtracking algorithm to find a solution to the 8 Queen problem.
Step 2: The algorithm starts by placing a queen on the first column, then it proceeds to the next column
and places a queen in the first safe row of that column.
Step 3: If the algorithm reaches the 8th column and all queens are placed in a safe position; it prints the
board and returns true.
Step 4: If the algorithm is unable to place a queen in a safe position in a certain column, it backtracks to
the previous column and tries a different row.
Step 5: The “isSafe” function checks if it is safe to place a queen on a certain row and column by checking
if there are any queens in the same row, diagonal or anti-diagonal.
Step 6: Finally, after placing all Queens safely on the board, Stop the Program.

Program:
N = 8 # (size of the chessboard)

def solveNQueens(board, col):


if col == N:
print(board)
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQueens(board, col + 1):
return True
board[i][col] = 0
return False

def isSafe(board, row, col):


for x in range(col):
if board[row][x] == 1:
return False
for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
if board[x][y] == 1:
return False
for x, y in zip(range(row, N, 1), range(col, -1, -1)):
if board[x][y] == 1:
return False
return True

board = [[0 for x in range(N)] for y in range(N)]


if not solveNQueens(board, 0):
print("No solution found")

ARTIFICIAL INTELLIGENCE | LABORATORY


2
Sample Output:
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]

Result:
Thus, the implementation of basic search strategies to the 8 - Queens problem was solved and
the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


3

Implement A* and memory bounded A* algorithms for 8-puzzle


2 Date:
problem

Aim:
To implementing A* and memory bounded A* algorithms for solving the 8-puzzle problem using
python programming.

Algorithm:
Step 1: Start the program.
Step 2: Define a list OPEN. Initially, OPEN consists solely of a single node, the start node S. A* Algorithm
works as-
 It maintains a tree of paths originating at the start node.
 It extends those paths one edge at a time.
 It continues until its termination criterion is satisfied.
Step 3: If the list is empty, return failure and exit.

Step 4: Remove node n with the smallest value of f(n) from OPEN and move it to list CLOSED. If node n
is a goal state, return success and exit.

Step 5: Expand node n.

Step 6: If any successor to n is the goal node, return success and the solution by tracing the path from
goal node to S. Otherwise, go to Step-5.

Step 7: For each successor node, Apply the evaluation function f to the node. A* Algorithm extends the
path that minimizes the following function- f(n) = g(n) + h(n)

Here,
 ‘n’ is the last node on the path
 g(n) is the cost of the path from start node to node ‘n’
 h(n) is a heuristic function that estimates cost of the cheapest path from node ‘n’ to the goal
node
Step 8: Go back to Step-3.

Program:
import copy
from heapq import heappush, heappop
n=3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
def __init__(self):
self.heap = []
def push(self, k):
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:

ARTIFICIAL INTELLIGENCE | LABORATORY


4
return False
class node:

def __init__(self, parent, mat, empty_tile_pos,


cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
def __lt__(self, nxt):
return self.cost < nxt.cost
def calculateCost(mat, final) -> int:
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
def newNode(mat, empty_tile_pos, new_empty_tile_pos,
level, parent, final) -> node:
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]
cost = calculateCost(new_mat, final)
new_node = node(parent, new_mat, new_empty_tile_pos, cost, level)
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
def isSafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
def solve(initial, empty_tile_pos, final):
pq = priorityQueue()
cost = calculateCost(initial, final)
root = node(None, initial, empty_tile_pos, cost, 0)
pq.push(root)

ARTIFICIAL INTELLIGENCE | LABORATORY


5
while not pq.empty():
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]

if isSafe(new_tile_pos[0], new_tile_pos[1]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
solve(initial, empty_tile_pos, final)
Sample Output:

1 2 3
5 6 0
7 8 4

1 2 3
5 0 6
7 8 4

1 2 3
5 8 6
7 0 4

1 2 3
5 8 6
0 7 4

Result:
Thus, the implementation of A* and memory bounded A* algorithms to the 8 - Puzzle problem
was solved and the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


6

Implement the Minimax algorithm for Tic-Tac-Toe game playing


3 Date:
(Alpha-Beta pruning)

Aim:
To implementing the Minimax algorithm for playing the Tic-Tac-Toe game (Alpha-Beta pruning)
by using Python programming.

Algorithm:
Step 1: The game is to be played between two people (in this program between HUMAN vs HUMAN).
Step 2: One of the players chooses ‘O’ and the other ‘X’ to mark their respective cells.
Step 3: The game starts with one of the players and the game ends when one of the players has one
whole row/ column/ diagonal filled with his/her respective character (‘O’ or ‘X’).
Step 4: If no one wins, then the game is said to be draw.
Step 5:

Program:
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]

def print_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])

def take_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Invalid input. Choose a position from 1-9: ")
position = int(position) - 1
while board[position] != "-":
position = int(input("Position already taken. Choose a different position: ")) - 1
board[position] = player
print_board()

def check_game_over():
# Check for a win
if (board[0] == board[1] == board[2] != "-") or \
(board[3] == board[4] == board[5] != "-") or \

ARTIFICIAL INTELLIGENCE | LABORATORY


7
(board[6] == board[7] == board[8] != "-") or \
(board[0] == board[3] == board[6] != "-") or \
(board[1] == board[4] == board[7] != "-") or \
(board[2] == board[5] == board[8] != "-") or \
(board[0] == board[4] == board[8] != "-") or \
(board[2] == board[4] == board[6] != "-"):
return "win"
elif "-" not in board:
return "tie"
# Game is not over
else:
return "play"

def play_game():
print_board()
current_player = "X"
game_over = False
while not game_over:
take_turn(current_player)
game_result = check_game_over()
if game_result == "win":
print(current_player + " wins!")
game_over = True
elif game_result == "tie":
print("It's a tie!")
game_over = True
else:
current_player = "O" if current_player == "X" else "X"

# Start the game


play_game()

Sample Output:

-|-|-
-|-|-
-|-|-
X's turn.
Choose a position from 1-9: 1
X|-|-
-|-|-
-|-|-
O's turn.
Choose a position from 1-9: 4
X|-|-
O|-|-
-|-|-
X's turn.
Choose a position from 1-9: 2

ARTIFICIAL INTELLIGENCE | LABORATORY


8
X|X|-
O|-|-
-|-|-
O's turn.
Choose a position from 1-9: 3
X|X|O
O|-|-
-|-|-
X's turn.
Choose a position from 1-9: 5
X|X|O
O|X|-
-|-|-
O's turn.
Choose a position from 1-9: 7
X|X|O
O|X|-
O|-|-
X's turn.
Choose a position from 1-9: 8
X|X|O
O|X|-
O|X|-
X wins!
>

Result:
Thus, the implementation of the Minimax algorithm for playing the Tic-Tac-Toe game was
solved and the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


9

Implement the Constraints Satisfaction Problem algorithm for


4 Date:
Sudoku Solver game playing

Aim:
To implementing the Constraints Satisfaction Problem algorithm for playing the Sudoku Solver
game by using Python programming.

Algorithm:
Step 1: Start the Implementation of Constraint Satisfaction Problems algorithms with code.
Step 2: Define the Problem
Step 3: Define Variables for the Constraint Satisfaction Problem
 The finite set of variables V1, V2, V3 ……………..Vn.
 Non-empty domain for every single variable D1, D2, D3 …………..Dn.
 The finite set of constraints C1, C2 …….…, Cm.
 where each constraint Ci restricts the possible values for variables,
 e.g., V1 ≠ V2
 Each constraint Ci is a pair <scope, relation>
 Example: <(V1, V2), V1 not equal to V2>
 Scope = set of variables that participate in constraint.
 Relation = list of valid variable value combinations.
 There might be a clear list of permitted combinations. Perhaps a relation that is abstract and that
allows for membership testing and listing.
Step 4: Define the Constraint for Constraint Satisfaction Problem
[[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 0, 0] ]
Step 5: Find the solution to the above Sudaku Problem

Program:
puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 0, 0]
]
def print_sudoku(puzzle):
for i in range(9):
if i % 3 == 0 and i != 0:

ARTIFICIAL INTELLIGENCE | LABORATORY


10
print("- - - - - - - - - - - ")
for j in range(9):
if j % 3 == 0 and j != 0:
print(" | ", end="")
print(puzzle[i][j], end=" ")
print()
print_sudoku(puzzle)
class CSP:
def __init__(self, variables, Domains,constraints):
self.variables = variables
self.domains = Domains
self.constraints = constraints
self.solution = None
def solve(self):
assignment = {}
self.solution = self.backtrack(assignment)
return self.solution
def backtrack(self, assignment):
if len(assignment) == len(self.variables):
return assignment
var = self.select_unassigned_variable(assignment)
for value in self.order_domain_values(var, assignment):
if self.is_consistent(var, value, assignment):
assignment[var] = value
result = self.backtrack(assignment)
if result is not None:
return result
del assignment[var]
return None
def select_unassigned_variable(self, assignment):
unassigned_vars = [var for var in self.variables if var not in assignment]
return min(unassigned_vars, key=lambda var: len(self.domains[var]))
def order_domain_values(self, var, assignment):
return self.domains[var]
def is_consistent(self, var, value, assignment):
for constraint_var in self.constraints[var]:
if constraint_var in assignment and assignment[constraint_var] == value:
return False
return True
variables = [(i, j) for i in range(9) for j in range(9)]
Domains = {var: set(range(1, 10)) if puzzle[var[0]][var[1]] == 0
else {puzzle[var[0]][var[1]]} for var in variables}
def add_constraint(var):
constraints[var] = []
for i in range(9):
if i != var[0]:
constraints[var].append((i, var[1]))
if i != var[1]:
constraints[var].append((var[0], i))

ARTIFICIAL INTELLIGENCE | LABORATORY


11
sub_i, sub_j = var[0] // 3, var[1] // 3
for i in range(sub_i * 3, (sub_i + 1) * 3):
for j in range(sub_j * 3, (sub_j + 1) * 3):
if (i, j) != var:
constraints[var].append((i, j))
constraints = {}
for i in range(9):
for j in range(9):
add_constraint((i, j))
print('*'*7,'Solution','*'*7)
csp = CSP(variables, Domains, constraints)
sol = csp.solve()
solution = [[0 for i in range(9)] for i in range(9)]
for i,j in sol:
solution[i][j]=sol[i,j]
print_sudoku(solution)

Sample Output:
530 |070 |000
600 |195 |000
098 |000 |060
-----------
800 |060 |003
400 |803 |001
700 |020 |006
-----------
060 |000 |280
000 |419 |005
000 |080 |000

******* Solution *******


534 |678 |192
672 |195 |348
198 |342 |567
-----------
859 |761 |423
426 |853 |971
713 |924 |856
-----------
961 |537 |284
287 |419 |635
345 |286 |719

Result:
Thus, the implementation of the Constraints Satisfaction Problem algorithm for playing the
Sudoku Solver game was solved and the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


12

Implement the Wumpus Game Using propositional model


5 Date:
checking algorithms

Aim:
To implementing the propositional model checking algorithm for playing the Wumpus game by
using Python programming.

Algorithm:
Step 1 : Find all pure symbols and eliminate all clauses with the pure symbol.
Step 2 : Find all unit clauses and terminate if there are conflicting unit clauses like p~p if not, remove
the unit clauses, clauses containing the literal and negation of the literal from the clauses which
contained it. check for length of knowledge base : if zero return true, check length of all clauses , if any
are zero return false
Step 3 : Do the above process recursively until there are no pure symbol/unit clauses to remove
Step 4: Pick a literal and assign a value to the literal. Remove clauses which contain the literal and
remove the negated forms from the respective clauses.
Step 5: Repeat from step1
Step 6: Return true if satisfying assignment has been found and assign a different value from that of step
4 and do the same again return true if satisfying assignment has been found
Step 7 : No satisfying assignment was found. Return false.

Program:
class Agent:
def __init__(self):
self._wumpusWorld = [
['','','',''], # Rooms [1,1] to [4,1]
['','W','P',''], # Rooms [1,2] to [4,2]
['','','',''], # Rooms [1,3] to [4,3]
['','','',''], # Rooms [1,4] to [4,4]
] # This is the wumpus world shown in the assignment question.
# A different instance of the wumpus world will be used for evaluation.
self._curLoc = [1,1]
self._isAlive = True
self._hasExited = False

def _FindIndicesForLocation(self,loc):
x,y = loc
i,j = y-1, x-1
return i,j

def _CheckForPitWumpus(self):
ww = self._wumpusWorld
i,j = self._FindIndicesForLocation(self._curLoc)
if 'P' in ww[i][j] or 'W' in ww[i][j]:
print(ww[i][j])
self._isAlive = False
print('Agent is DEAD.')
return self._isAlive

ARTIFICIAL INTELLIGENCE | LABORATORY


13
def TakeAction(self,action): # The function takes an action and returns whether the Agent is alive
# after taking the action.
validActions = ['Up','Down','Left','Right']
assert action in validActions, 'Invalid Action.'
if self._isAlive == False:
print('Action cannot be performed. Agent is DEAD. Location:{0}'.format(self._curLoc))
return False
if self._hasExited == True:
print('Action cannot be performed. Agent has exited the Wumpus world.'.format(self._curLoc))
return False

index = validActions.index(action)
validMoves = [[0,1],[0,-1],[-1,0],[1,0]]
move = validMoves[index]
newLoc = []
for v, inc in zip(self._curLoc,move):
z = v + inc #increment location index
z = 4 if z>4 else 1 if z<1 else z #Ensure that index is between 1 and 4
newLoc.append(z)
self._curLoc = newLoc
print('Action Taken: {0}, Current Location {1}'.format(action,self._curLoc))
if self._curLoc[0]==4 and self._curLoc[1]==4:
self._hasExited=True
return self._CheckForPitWumpus()

def _FindAdjacentRooms(self):
cLoc = self._curLoc
validMoves = [[0,1],[0,-1],[-1,0],[1,0]]
adjRooms = []
for vM in validMoves:
room = []
valid = True
for v, inc in zip(cLoc,vM):
z = v + inc
if z<1 or z>4:
valid = False
break
else:
room.append(z)
if valid==True:
adjRooms.append(room)
return adjRooms

def PerceiveCurrentLocation(self): #This function perceives the current location.


#It tells whether breeze and stench are present in the current location.
breeze, stench = False, False
ww = self._wumpusWorld
if self._isAlive == False:

ARTIFICIAL INTELLIGENCE | LABORATORY


14
print('Agent cannot perceive. Agent is DEAD. Location:{0}'.format(self._curLoc))
return [None,None]
if self._hasExited == True:
print('Agent cannot perceive. Agent has exited the Wumpus World.'.format(self._curLoc))
return [None,None]

adjRooms = self._FindAdjacentRooms()
for room in adjRooms:
i,j = self._FindIndicesForLocation(room)
if 'P' in ww[i][j]:
breeze = True
if 'W' in ww[i][j]:
stench = True
return [breeze,stench]

def FindCurrentLocation(self):
return self._curLoc

def main():
ag = Agent()
print('curLoc',ag.FindCurrentLocation())
print('Percept [breeze, stench] :',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Right')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
ag.TakeAction('Up')
print('Percept',ag.PerceiveCurrentLocation())
if __name__=='__main__':
main()

Sample Output:
curLoc [1, 1]
Percept [breeze, stench] : [False, False]
Action Taken: Right, Current Location [2, 1]
Percept [False, True]
Action Taken: Right, Current Location [3, 1]
Percept [True, False]
Action Taken: Right, Current Location [4, 1]
Percept [False, False]
Action Taken: Up, Current Location [4, 2]
Percept [True, False]
Action Taken: Up, Current Location [4, 3]

ARTIFICIAL INTELLIGENCE | LABORATORY


15
Percept [False, False]
Action Taken: Up, Current Location [4, 4]
Agent cannot perceive. Agent has exited the Wumpus World.
Percept [None, None]

Result:
Thus, the implementation of the propositional model checking algorithm for playing the
Wumpus game was solved and the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


16

Implement the Fishy Expert System Shell Using Forward


6 Date:
chaining, Backward chaining and resolution Strategies

Aim:
To implementing the Forward chaining, Backward chaining and resolution Strategies for playing
the Fishy Expert System Shell by using Python programming.

Algorithm:
Step 1: Start program
Step 2: This is a rule-based expert system shell. It can be used for diagnostics among other things.
Step 3: Knowledge Base : Hypotheses and Facts are referred to as Atoms, and each one of them is
expected in one of the following formats: <key> <key>: <statement> <key>: <statement>. <truth value>.
Step 4: Inference Engine: Forward-chaining algorithm is irrevocable, uses a depth-first search strategy,
and favors rules with most premises in selection.
Step 5: Graphical User Interface: The built-in text editor makes it possible to view and directly alter the
Knowledge Base, with options to cancel or save the changes.
Step 6: Stop the program.
Program:
from collections import OrderedDict
class Variable:
def __init__(self, value, truth, root):
self.value = value
self.truth = truth
self.root = root
def get_value(self):
return self.value
def get_truth(self):
return self.truth
def get_root(self):
return self.root
def set_truth(self, truth):
self.truth = truth
def __str__(self):
return "{ value = " + self.value + ", truth = " + str(self.truth) + ", root = " + str(self.root) + " }"
def __repr__(self):
return str(self)
class Rule:
def __init__(self, antecedent, consequent):
self.antecedent = antecedent
self.consequent = consequent
def get_antecedent(self):
return self.antecedent
def get_consequent(self):

ARTIFICIAL INTELLIGENCE | LABORATORY


17
return self.consequent
def __str__(self):
return str(self.antecedent) + " -> " + str(self.consequent)
def __repr__(self):
return str(self)
def valid_rule(antecedent, consequent, variables):
antecedent = antecedent.replace("(", " ( ")
antecedent = antecedent.replace(")", " ) ")
antecedent = antecedent.replace("&", " AND ")
antecedent = antecedent.replace("|", " OR ")
antecedent = antecedent.replace("!", " NOT ")
antecedent = antecedent.split()
for a in antecedent:
if a not in ["(", ")", "AND", "OR", "NOT"]:
if a not in variables:
return False
if consequent not in variables or variables[consequent].get_root():
return False
return True
def reset_learned(variables):
for key in variables:
if not variables[key].get_root():
variables[key].set_truth(False)
def is_fact(var, variables):
if var in variables and variables[var].get_truth():
return True
else:
return False
def format_rule(antecedent, consequent, variables, rules):
valid = query_exp(consequent, variables, rules)
antecedent = antecedent.replace("(", " ( ")
antecedent = antecedent.replace(")", " ) ")
antecedent = antecedent.replace("&", " AND ")
antecedent = antecedent.replace("|", " OR ")
antecedent = antecedent.replace("!", " NOT ")
antecedent = antecedent.split()
for i in range(len(antecedent)):
if antecedent[i] not in ["(", ")", "AND", "OR", "NOT"]:
antecedent[i] = variables[antecedent[i]].get_value()
if antecedent[0] == "NOT":
new_ant = str(antecedent[0]) + " "

ARTIFICIAL INTELLIGENCE | LABORATORY


18
else:
new_ant = str(antecedent[0])
for a in range(1, len(antecedent)):
if antecedent[a] in ["AND", "OR"]:
new_ant += " " + str(antecedent[a]) + " "
elif antecedent[a] == "NOT":
new_ant += str(antecedent[a]) + " "
else:
new_ant += str(antecedent[a])
antecedent = new_ant
if valid:
return "BECAUSE " + antecedent + " I KNOW THAT " + variables[consequent].get_value()
else:
return "BECAUSE IT IS NOT TRUE THAT " + antecedent + " I CANNOT PROVE THAT " +
variables[consequent].get_value()
def format_goal(goal, variables):
goal = goal.replace("(", " ( ")
goal = goal.replace(")", " ) ")
goal = goal.replace("&", " AND ")
goal = goal.replace("|", " OR ")
goal = goal.replace("!", " NOT ")
goal = goal.split()
for i in range(len(goal)):
if goal[i] not in ["(", ")", "AND", "OR", "NOT"]:
goal[i] = variables[goal[i]].get_value()
if goal[0] == "NOT":
new_goal = str(goal[0]) + " "
else:
new_goal = str(goal[0])
for g in range(1, len(goal)):
if goal[g] in ["AND", "OR"]:
new_goal += " " + str(goal[g]) + " "
elif goal[g] == "NOT":
new_goal += str(goal[g]) + " "
else:
new_goal += str(goal[g])
return new_goal
def solve(expression, variables):
expression = expression.replace('(', '( ')
expression = expression.replace(')', ' )')
expression = expression.replace('&', ' and ')

ARTIFICIAL INTELLIGENCE | LABORATORY


19
expression = expression.replace('|', ' or ')
expression = expression.replace('!', 'not ')
expression_list = expression.split()
for i in range(len(expression_list)):
if expression_list[i] not in ['not', 'or', 'and', '(', ')']:
expression_list[i] = variables[expression_list[i]].get_truth()
expression = str(expression_list[0]) + " "
for i in range(1, len(expression_list)):
expression += str(expression_list[i]) + " "
return eval(expression)
def query_exp(expression, variables, rules, why=False):
expression = expression.replace('(', '( ')
expression = expression.replace(')', ' )')
expression = expression.replace('&', ' and ')
expression = expression.replace('|', ' or ')
expression = expression.replace('!', 'not ')
expression_list = expression.split()
for i in range(len(expression_list)):
if expression_list[i] not in ['not', 'or', 'and', '(', ')']:
found = False
for rule in rules:
if rule.get_consequent() == expression_list[i]:
found = True
expression_list[i] = query_exp(rule.get_antecedent(), variables, rules)
if not found:
expression_list[i] = variables[expression_list[i]].get_truth()
expression = str(expression_list[0]) + " "
for i in range(1, len(expression_list)):
expression += str(expression_list[i]) + " "
return eval(expression)
def why_exp(expression, variables, rules, start=False):
result = list()
if start and query_exp(expression, variables, rules):
reasoning = "I THUS KNOW THAT "
elif start:
reasoning = "THUS I CANNOT PROVE "
temp = expression.replace('(', '( ')
temp = temp.replace(')', ' )')
temp = temp.replace('&', ' and ')
temp = temp.replace('|', ' or ')
temp = temp.replace('!', 'not ')

ARTIFICIAL INTELLIGENCE | LABORATORY


20
exp_list = temp.split()
print(exp_list)
for i in range(len(exp_list)):
if exp_list[i] not in ['&', '|', '!', '(', ')']:
exp_list[i] = variables[exp_list[i]].get_value()
for x in exp_list:
reasoning += str(x)
reasoning = reasoning.replace('(', ' ( ')
reasoning = reasoning.replace(')', ' ) ')
reasoning = reasoning.replace('&', ' AND ')
reasoning = reasoning.replace('|', ' OR ')
reasoning = reasoning.replace('!', ' NOT ')
result.append(reasoning)
count = 0
addition, count = simplify(expression, variables, rules, count)
result.extend(addition)
return result, count
def determine_why(expression, variables, rules):
valid = query_exp(expression, variables, rules)
logic = list()
logic.append(expression)
done = False
expression = expression.replace('(', ' ( ')
expression = expression.replace(')', ' ) ')
expression = expression.replace('&', ' & ')
expression = expression.replace('|', ' | ')
expression = expression.replace('!', ' ! ')
exp_list = expression.split()
while not done:
done = True
change = False
for i in range(len(exp_list)):
if exp_list[i] not in ['!', '|', '&', '(', ')'] and not variables[exp_list[i]].get_truth():
for rule in rules:
if rule.get_consequent() == exp_list[i]:
exp_list[i] = rule.get_antecedent()
exp_list[i] = exp_list[i].replace('(', ' ( ')
exp_list[i] = exp_list[i].replace(')', ' ) ')
exp_list[i] = exp_list[i].replace('&', ' & ')
exp_list[i] = exp_list[i].replace('|', ' | ')
exp_list[i] = exp_list[i].replace('!', ' ! ')

ARTIFICIAL INTELLIGENCE | LABORATORY


21
exp_list[i] = exp_list[i].split()
exp_list = exp_list[:i] + exp_list[i] + exp_list[i+1:]
done = False
change = True
break
if change:
str_exp = str(exp_list[0])
for i in range(1, len(exp_list)):
str_exp += str(exp_list[i])
logic.append(str_exp)
change = False
return valid, logic
def get_diff(a, b):
unique = ""
a = a.replace('(', ' ( ')
a = a.replace(')', ' ) ')
a = a.replace('&', ' & ')
a = a.replace('|', ' | ')
a = a.replace('!', ' ! ')
a = a.split()
for i in a:
if i not in b and i not in ['!', '|', '&', '(', ')']:
unique = i
return unique
if __name__ == "__main__":
print("\n\t\tHello! I'm Halal-bot, and I'm smarter than you.", end='\n\n')
var_list = OrderedDict()
rule_list = list()
while True:
teach_var = False
set_root = False
teach_rule = False
list_knowledge = False
learn = False
query = False
why = False
index = None
user_input = input("Enter a new definition, fact, or rule: ").split('"')
if user_input[0] == '':
break
args = user_input[0].split()

ARTIFICIAL INTELLIGENCE | LABORATORY


22
if len(user_input) > 1:
args.append(user_input[1])
if len(args) != 5:
continue
teach_var = True
if len(args) == 1:
if args[0] == 'List':
list_knowledge = True
if args[0] == 'Learn':
learn = True
if len(args) == 2:
if args[0] == 'Query':
query = True
if args[0] == 'Why':
why = True
if not teach_var:
for i in range(len(args)):
if args[i] == '=':
set_root = True
index = i
if args[i] == '->':
teach_rule = True
index = i
if teach_var:
var_defined = False
for key in var_list:
if key == args[2]:
print("\nVariable already defined.")
var_defined = True
if var_defined:
continue
if args[1] == '-R':
var_list[args[2]] = Variable(args[4], False, True)
else:
var_list[args[2]] = Variable(args[4], False, False)
elif set_root:
if args[1] not in var_list:
print("\nVariable not defined.")
continue
if var_list[args[1]].get_root():
if args[3] == 'true':

ARTIFICIAL INTELLIGENCE | LABORATORY


23
var_list[args[1]].set_truth(True)
reset_learned(var_list)
elif args[3] == 'false':
var_list[args[1]].set_truth(False)
reset_learned(var_list)
else:
print("\nInvalid assignment. Assign 'true' or 'false.'")
else:
print("\n" + str(args[1]) + " is not a root variable.")
elif teach_rule:
antecedent = args[1]
consequent = args[-1]
if valid_rule(antecedent, consequent, var_list):
rule_list.append(Rule(antecedent, consequent))
else:
continue
elif list_knowledge:
print("\nRoot Variables:")
for key in var_list:
if var_list[key].get_root():
print("\t" + key + " = " + '"' + var_list[key].get_value() + '"')
print("\nLearned Variables:")
for key in var_list:
if not var_list[key].get_root():
print("\t" + key + " = " + '"' + var_list[key].get_value() + '"')
print("\nFacts:")
for key in var_list:
if var_list[key].get_truth():
print("\t" + key)
print("\nRules:")
for rule in rule_list:
print("\t" + rule.__str__())
elif learn:
for rule in rule_list:
if solve(rule.get_antecedent(), var_list):
var_list[rule.get_consequent()].set_truth(True)
else:
var_list[rule.get_consequent()].set_truth(False)
elif query:
print("\n" + str(query_exp(args[1], var_list, rule_list)))

ARTIFICIAL INTELLIGENCE | LABORATORY


24
elif why:
valid, logic = determine_why(args[1], var_list, rule_list)
print("\n" + str(valid)
fact_list = list()
for step in logic:
step = step.replace("(", " ( ")
step = step.replace(")", " ) ")
step = step.replace("&", " & ")
step = step.replace("|", " | ")
step = step.replace("!", " ! ")
step = step.split()
for i in step:
if i not in ["(", ")", "&", "|", "!"] and i not in fact_list and var_list[i].get_root():
fact_list.append(i)
for fact in fact_list:
if var_list[fact].get_truth():
print("I KNOW THAT " + var_list[fact].get_value())
else:
print("I KNOW IT IS NOT TRUE THAT " + var_list[fact].get_value())
i = len(logic)-1
while i >= 0:
if i > 0:
con = get_diff(logic[-2], logic[-1])
ant = ""
for rule in rule_list:
if rule.get_consequent() == con:
ant = rule.get_antecedent()
print(format_rule(ant, con, var_list, rule_list))
else:
if valid:
print("I THUS KNOW THAT", format_goal(logic[0], var_list))
else:
print("THUS I CANNOT PROVE", format_goal(logic[0], var_list))
i -= 1
logic.pop()
else:
print("\nHaram Command.")
print()
Sample Output:
Hello! I'm Halal-bot, and I'm smarter than you.
Enter a new definition, fact, or rule: "Matt likes ice cream"

ARTIFICIAL INTELLIGENCE | LABORATORY


25
'Matt likes ice cream'

Result:
Thus, the implementation of Forward chaining, Backward chaining and resolution Strategies for
playing the Fishy Expert System Shell and the output was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


26

Implement the Naïve Bayes model with probabilistic reasoning


7 Date:
based on Bayes theorem

Aim:
To build Naïve Bayes model with probabilistic reasoning based on Bayes theorem by using
Python programming.

Algorithm:
Step1: Calculate the prior probability for given class labels.
Step2: Find Likelihood probability with each attribute for each class.
Step3: Put these values in Bayes Formula and calculate posterior probability.
Step4: See which class has a higher probability, given the input belongs to the higher probability class.
Step5: Testing and evaluation of the model.
Program:
Def bayesTheorem(pA,pB,pBA):
return pA*pBA/pB
#define function for Bayes theorem
def bayesTheorem(pA,pB,pBA):
return pA*pBA/pB
#define probabilities
pRain=0.2
pcloudy=0.4
pcloudyRain=0.85
#use function to calculate conditional probability
bayesTheorem(pRain,pcloudy,pcloudyRain)
0.425

Sample Output:

The probability that it will rain that day is 0.425 or 42.5

Result:
Thus, the implementation of Naïve Bayes model with probabilistic reasoning based on Bayes
theorem executed successfully and output was verified using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


27

Implement the Bayesian network a manual construction or


8 Date:
automatic construction

Aim:
To build a Bayesian network a manual construction or automatic construction (so called
"learning") from databases by using Python programming.

Algorithm:
Step 1:Identify which are the main variable in the problem to solve.
Step2:Define structure of the network, that is, the causal relationships between all the variables (nodes).
Step3:Define the probability rules governing the relationships between the variables.
Program:
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
import networkx as nx
import pylab as plt
#Defining Bayesian Structure
model = BayesianNetwork([('Guest', 'Host'), ('Price', 'Host')])
#Defining the CPDs:
cpd_guest = TabularCPD('Guest', 3, [[0.33], [0.33], [0.33]])
cpd_price = TabularCPD('Price', 3, [[0.33], [0.33], [0.33]])
cpd_host = TabularCPD('Host', 3, [[0, 0, 0, 0, 0.5, 1, 0, 1, 0.5],
[0.5, 0, 1, 0, 0, 0, 1, 0, 0.5],
[0.5, 1, 0, 1, 0.5, 0, 0, 0, 0]],
evidence=['Guest', 'Price'], evidence_card=[3, 3])
#Associating the CPDs with the network structure.
model.add_cpds(cpd_guest, cpd_price, cpd_host)
model.check_model()
#Infering the posterior probability
from pgmpy.inference import VariableElimination
infer = VariableElimination(model)
posterior_p = infer.query(['Host'], evidence={'Guest': 2, 'Price': 2})
print(posterior_p)

ARTIFICIAL INTELLIGENCE | LABORATORY


28
Sample Output:

nx.draw(model, with_labels=True)
plt.savefig('model.png')
plt.close()

This gives us the Directed Acyclic Graph (DAG) as like below.

Result:
Thus, the implementation of Bayesian network a manual construction or automatic construction
was executed successfully and output was verified using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


29

9 Mini Project - Number Guessing Game Date:

Aim:
To build a Number guessing game using python in which the user selects a range and some
random integer will be selected by the system and the user has to guess that integer in the minimum
number of guesses.

Algorithm:
STEP 1:User inputs the lower bound and upper bound of the range.
STEP 2:The compiler generates a random integer between the range and store it in a variable for future
references.
STEP 3:For repetitive guessing, a while loop will be initialized.
STEP 4:If the user guessed a number which is greater than a randomly selected number, the user gets
an output “Try Again! You guessed too high“
STEP 5:Else If the user guessed a number which is smaller than a randomly selected number, the user
gets an output “Try Again! You guessed too small”
STEP 6:And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ”
Output.
STEP 7:Else if the user didn’t guess the integer in the minimum number of guesses, he/she will get
“Better Luck Next Time!” output.

Program:
import random
import math
# Taking Inputs
lower = int(input("Enter Lower bound:- "))

# Taking Inputs
upper = int(input("Enter Upper bound:- "))

# generating random number between


# the lower and upper
x = random.randint(lower, upper)
print("\n\tYou've only ",
round(math.log(upper - lower + 1, 2)),
" chances to guess the integer!\n")

# Initializing the number of guesses.


count = 0

# for calculation of minimum number of


# guesses depends upon range
while count < math.log(upper - lower + 1, 2):
count += 1

# taking guessing number as input


guess = int(input("Guess a number:- "))

# Condition testing

ARTIFICIAL INTELLIGENCE | LABORATORY


30
if x == guess:
print("Congratulations you did it in ",
count, " try")
# Once guessed, loop will break
break
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")

# If Guessing is more than required guesses,


# shows this output.
if count >= math.log(upper - lower + 1, 2):
print("\nThe number is %d" % x)
print("\tBetter Luck Next time!")

Sample Output:

Result:
Thus, the implementation of the Number guessing game was solved and the output was executed
successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY


31

CONTENT BEYOND SYLLABUS

ARTIFICIAL INTELLIGENCE | LABORATORY


32

10 Tower of Hanoi Solve Using AI Techniques Date:

Aim:
To implementing the Tower of Hanoi using AI Techniques by using Python programming.

Algorithm:
Problem: -
Tower of Hanoi is a mathematical problem (puzzle) that consists of 3 poles and ‘n’ number of
discs, each disc having different diameters.
Objective: -
The objective or goal of this problem is to transfer all the ‘n’ discs from source pole to the
destination pole in such a way that we get the same arrangement of discs as before. But this goal must
be achieved by sticking to the rules.
Rule: -
 Only one disc can be moved at a time.
 Only the top-most disc can be removed
 The larger disc cannot be placed on top of the smaller disc.

Step1: Start the program

Step 2: Create a tower_of_hanoi recursive function and pass two arguments: the number of disks n and
the name of the rods such as source, aux, and target.

Step 3: We can define the base case when the number of disks is 1. In this case, simply move the one
disk from the source to target and return.

Step 4: Now, move remaining n-1 disks from source to auxiliary using the target as the auxiliary.

Step 5: Then, the remaining 1 disk move on the source to target.

Step 6: Move the n-1 disks on the auxiliary to the target using the source as the auxiliary.

Step 7: Stop the program.


Program:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1, fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1, withPole,toPole,fromPole)

ARTIFICIAL INTELLIGENCE | LABORATORY


33
def moveDisk(fp,tp):
print ("moving disk from”, fp,"to”, tp)
moveTower(3,"A","B","C")
Sample Output:

Result:
Thus, the implementation of the Tower of Hanoi using AI Techniques was solved and the output
was executed successfully using Python Program.

ARTIFICIAL INTELLIGENCE | LABORATORY

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