Ad3311 - Artificial Intelligence Laboratory-6-38
Ad3311 - Artificial Intelligence Laboratory-6-38
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)
Result:
Thus, the implementation of basic search strategies to the 8 - Queens problem was solved and
the output was executed successfully using Python Program.
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 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:
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.
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 \
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"
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
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.
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:
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
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.
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
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
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]
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.
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):
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.
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:
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.
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)
nx.draw(model, with_labels=True)
plt.savefig('model.png')
plt.close()
Result:
Thus, the implementation of Bayesian network a manual construction or automatic construction
was executed successfully and output was verified using Python Program.
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:- "))
# Condition testing
Sample Output:
Result:
Thus, the implementation of the Number guessing game was solved and the output was executed
successfully using Python Program.
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.
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 6: Move the n-1 disks on the auxiliary to the target using the source as the auxiliary.
Result:
Thus, the implementation of the Tower of Hanoi using AI Techniques was solved and the output
was executed successfully using Python Program.