AI&Apps Journal
AI&Apps Journal
OUTPUT:
b.) Implement breadth first search algorithm.
Code:
graph1= {
'A': ['B','E','C'],
'B': ['A','D','E'],
'C': ['A','F','G'],
'D': ['B','E'],
'E': ['A','B','D'],
'F': ['C'],
'G': ['C']
}
def bfs(graph, start, explored):
queue=[start]
while queue:
node=queue.pop(0)
if node not in explored:
explored.append(node)
for neighbour in graph[node]:
queue.append(neighbour)
return explored
explored1=bfs(graph1,'A',[ ])
print(explored1)
OUTPUT:
PRACTICAL NO: 2
Aim::Write programs for the following.
a.) Simulate 4-Queen / N-Queen problem.
Code:
class QueenChessBoard:
def __init__(self, size):
self.size=size
self.columns=[]
def place_in_next_row(self, column):
self.columns.append(column)
def remove_in_current_row(self):
return self.columns.pop()
def is_this_column_safe_in_next_row(self, column):
row=len(self.columns)
for queen_column in self.columns:
if column==queen_column:
return False
for queen_row, queen_column in enumerate(self.columns):
if queen_column - queen_row==column-row:
return False
for queen_row, queen_column in enumerate(self.columns):
if((self.size - queen_column)-queen_row==(self.size-column)-row):
return False
return True
def display(self):
for row in range(self.size):
for column in range(self.size):
if column==self.columns[row]:
print('Q', end=' ')
else:
print('.',end=' ')
print()
def solve_queen(size):
board=QueenChessBoard(size)
number_of_solutions=0
row=0
column=0
while True:
while column<size:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row+=1
column=0
break
else:
column+=1
if(column==size or row==size):
if row==size:
board.display()
print()
number_of_solutions+=1
board.remove_in_current_row()
row-=1
try:
prev_column=board.remove_in_current_row()
except IndexError:
break
row-=1
column=1+prev_column
print('Number of Solutions: ',number_of_solutions)
n=int(input('Enter n: '))
solve_queen(n)
OUTPUT:
b.) Solve tower of Hanoi problem.
Code:
def TowerOfHanoi(n, source, dest, aux):
if n==1:
print('Move one disk from node ',source,' to node ', dest)
return
TowerOfHanoi(n-1, source, aux, dest)
print('Move disk ',n,' from node ',source,' to node ', dest)
TowerOfHanoi(n-1, aux, dest, source)
n=3
TowerOfHanoi(n, 'A', 'B', 'C')
OUTPUT:
PRACTICAL NO: 3
Aim::Write programs for the following.
a.) Implement alpha beta search.
Code:
MAX,MIN=1000,-1000
def minimax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):
if depth==3:
return values[nodeIndex]
if maximizingPlayer:
best=MIN
for i in range(0,2):
val=minimax(depth+1,nodeIndex*2+i,False,values,alpha,beta)
best=max(best,val)
alpha=max(alpha,best)
if beta<=alpha:
break
return best
else:
best=MAX
for i in range(0,2):
val=minimax(depth+1,nodeIndex*2+i,True,values,alpha,beta)
best=min(best,val)
beta=min(beta,best)
if beta<=alpha:
break
return best
if __name__=="__main__":
values=[3,5,6,9,1,2,0,-1]
print("The optimal value is: ",minimax(0,0,True,values,MIN,MAX))
OUTPUT:
b.) Implement hill climbing problem.
Code:
import math
increment=0.1
startingPoint=[1,1]
point1=[1,5]
point2=[6,4]
point3=[5,2]
point4=[2,1]
def distance(x1,y1,x2,y2):
dist=math.pow(x2-x1,2)+math.pow(y2-y1,2)
return dist
def sumOfDistances(x1,y1,px1,py1,px2,py2,px3,py3,px4,py4):
d1=distance(x1,y1,px1,py1)
d2=distance(x1,y1,px2,py2)
d3=distance(x1,y1,px3,py3)
d4=distance(x1,y1,px4,py4)
return d1+d2+d3+d4
def newDistance(x1,y1,point1,point2,point3,point4):
d1=[x1,y1]
d1temp=sumOfDistances(x1,y1,point1[0],point1[1],point2[0],point2[1],point3[0]
,point3[1],point4[0],point4[1])
d1.append(d1temp)
return d1
minDistance=sumOfDistances(startingPoint[0],startingPoint[1],point1[0],point1[1],
point2[0],point2[1],point3[0],point3[1],point4[0],point4[1])
flag=True
def newPoints(minimum,d1,d2,d3,d4):
if d1[2]==minimum:
return[d1[0],d1[1]]
elif d2[2]==minimum:
return[d2[0],d2[1]]
elif d3[2]==minimum:
return[d3[0],d3[1]]
elif d4[2]==minimum:
return[d4[0],d4[1]]
i=1
while flag:
d1=newDistance(startingPoint[0]+increment,startingPoint[1],point1,point2,point3,
point4)
d2=newDistance(startingPoint[0]-increment
,startingPoint[1],point1,point2,point3,point4)
d3=newDistance(startingPoint[0],startingPoint[1]+increment,point1,point2,point3
,point4)
d4=newDistance(startingPoint[0],startingPoint[1]-increment
,point1 ,point2,point3,point4)
print(i,'',round(startingPoint[0],2),round(startingPoint[1],2))
minimum=min(d1[2],d2[2],d3[2],d4[2])
if minimum<minDistance:
startingPoint=newPoints(minimum,d1,d2,d3,d4)
minDistance=minimum
i+=1
else:
flag=False
OUTPUT:
PRACTICAL NO: 4
Aim::Write programs for the following.
a.) Implement A* algorithm.
Code:
from simpleai.search import SearchProblem,astar
GOAL="HELLO WORLD"
class HelloProblem(SearchProblem):
def actions(self,state):
if len(state)<len(GOAL):
return list(" ABCDEFGHIJKLMNOPQRSTUVWXYZ")
else:
return[]
def result(self,state,action):
return state+action
def is_goal(self,state):
return state==GOAL
def heuristic(self,state):
wrong=sum([1 if state[i]!=GOAL[i] else 0 for i in range(len(state))])
missing=len(GOAL)-len(state)
return wrong+missing
problem=HelloProblem(initial_state="")
result=astar(problem)
print(result.state)
print(result.path())
OUTPUT:
b.) Solve water jug problem.
Code:
def pour(jug1,jug2):
max1,max2,fill=5,7,4
print("%d\t%d"%(jug1,jug2))
if jug2 is fill:
return
elif jug2 is max2:
pour(0,jug1)
elif jug1!=0 and jug2 is 0:
pour(0,jug1)
elif jug1 is fill:
pour(jug1,0)
elif jug1<max1:
pour(max1,jug2)
elif jug1<(max2-jug2):
pour(0,(jug1+jug2))
else:
pour(jug1-(max2-jug2),(max2-jug2)+jug2)
print("JUG1\tJUG2")
pour(0,0)
OUTPUT:
PRACTICAL NO: 5
Aim::Write programs for the following.
a.) Simulate tic – tac – toe game using min-max algorithm.
Code:
import os
import time
board=[' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player=1
Win=1
Draw=-1
Running=0
Stop=1
Game=Running
Mark='X'
def DrawBoard():
print("%c|%c|%c"%(board[1],board[2],board[3]))
print("_|_|_")
print("%c|%c|%c"%(board[4],board[5],board[6]))
print("_|_|_")
print("%c|%c|%c"%(board[7],board[8],board[9]))
print("_|_|_")
def CheckPosition(X):
if(board[X]==' '):
return True
else:
return False
def CheckWin():
global Game
if(board[1]==board[2] and board[2]==board[3] and board[1]!=' '):
Game=Win
elif(board[4]==board[5] and board[5]==board[6] and board[4]!=' '):
Game=Win
elif(board[7]==board[8] and board[8]==board[9] and board[7]!=' '):
Game=Win
elif(board[1]==board[4] and board[4]==board[7] and board[1]!=' '):
Game=Win
elif(board[2]==board[5] and board[5]==board[8] and board[2]!=' '):
Game=Win
elif(board[3]==board[6] and board[6]==board[9] and board[3]!=' '):
Game=Win
elif(board[1]==board[5] and board[5]==board[9] and board[1]!=' '):
Game=Win
elif(board[3]==board[5] and board[5]==board[7] and board[3]!=' '):
Game=Win
elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and board[5]!=' ' and
board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '):
Game=Draw
else:
Game=Running
print("Tic-Tac-Toe Game")
print("Player1[X]...Player2[O]\n")
print()
print()
print("Please Wait...")
time.sleep(1)
while(Game==Running):
os.system('cls')
DrawBoard()
if(player%2!=0):
print("Player 1's Chance")
Mark='X'
else:
print("Player 2's Chance")
Mark='O'
choice=int(input("Enter position between [1-9] where you want to mark:"))
if(CheckPosition(choice)):
board[choice]=Mark
player+=1
CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
OUTPUT:
b.) Shuffle a deck of cards using the module random and draw 5 cards.
Code:
import itertools,random
deck=list(itertools.product(range(1,13),['Spade','Heart','Diamond','Club']))
random.shuffle(deck)
print("You got:")
for i in range(5):
print(deck[i][0],"of",deck[i][1])
OUTPUT:
PRACTICAL NO: 6
Aim::Write programs for the following.
a.) Derive the expressions based on Associative Law.
Code:
associative_law(A,B,C,Result):-
Result is A+(B+C).
expression1(2,3,4).
expression2(5,6,7).
derive_results:-
expression1(A,B,C),
associative_law(A,B,C,Result1),
expression2(X,Y,Z),
associative_law(X,Y,Z,Result2),
write('Result of expression1 using associative law: '),write(Result1),nl,
write('Result of expression1 using associative law: '),write(Result2),nl.
OUTPUT:
b.) Derive the expressions based on Distributive Law.
Code:
distributive_law(A,B,C,Result):-
Result is A*(B+C).
expression3(2,3,4).
expression4(5,6,7).
derive_results:-
expression3(A,B,C),
distributive_law(A,B,C,Result1),
expression4(X,Y,Z),
distributive_law(X,Y,Z,Result2),
write('Result of expression3 using distributive law: '),write(Result1),nl,
write('Result of expression4 using distributive law: '),write(Result2),nl.
OUTPUT:
PRACTICAL NO: 7
Aim::Write programs for the following.
a.) Derive the predicate.
i. for e.g.: Sachin is batsman, batsman is cricketer
- > Sachin is Cricketer.
Code:
batsman(sachin).
cricketer(X):-
batsman(X).
OUTPUT:
ii. for e.g.: Sachin is batsman, batsman is cricketer; Bumrah is baller, baller is
cricketer; & Dhoni is keeper, keeper is cricketer.
- >Sachin, Bumrah, and Dhoni are cricketers.
Code:
batsman(sachin).
baller(bumrah).
keeper(dhoni).
cricketer(X):-
batsman(X);
baller(X);
keeper(X).
OUTPUT:
PRACTICAL NO: 8
Aim::Write programs for the following.
a.) Write a program which contains three predicates: male, female, parent. Make
rules for following family relations: father, mother, grandfather, grandmother,
brother, sister, uncle, aunt, nephew and niece, cousin.
Question:
i. Draw Family Tree.
ii. Define: Clauses, Facts, Predicates and Rules with conjunction and
disjunction.
Code:
male(john).
male(robert).
male(hal).
male(jeff).
male(daniel).
male(zeke).
male(frank).
male(stanley).
male(george).
male(bobby).
male(brian).
female(jessica).
female(lana).
female(clara).
female(lillie).
female(ashley).
female(tammy).
female(lorrie).
female(melissa).
female(lisa).
female(annie).
parent(daniel,john).
parent(daniel,brian).
parent(daniel,jessica).
parent(charles,hal).
parent(frank,robert).
parent(frank,lana).
parent(frank,lisa).
parent(frank,lillie).
parent(lisa,john).
parent(lisa,brian).
parent(lisa,jessica).
parent(jessica,bobby).
parent(stanley,lisa).
parent(stanley,lana).
parent(george,daniel).
parent(george,zeke).
parent(zeke,jeff).
child(X,Y):-
parent(Y,X).
spouse(X,Y):-
child(P,X),child(P,Y).
husband(X,Y):-
male(X),spouse(X,Y).
wife(X,Y):-
female(X),spouse(X,Y).
son(X,Y):-
male(X),child(X,Y).
daughter(X,Y):-
female(X),child(X,Y).
mother(X,Y):-
female(X),parent(X,Y).
father(X,Y):-
male(X),parent(X,Y).
sibling(X,Y):-
parent(P,X),parent(P,Y),X\=Y.
brother(X,Y):-
male(X),sibling(X,Y).
sister(X,Y):-
female(X),sibling(X,Y).
grandmother(X,Y):-
mother(X,P),parent(P,Y).
grandfather(X,Y):-
father(X,P),parent(P,Y).
grandson(X,Y):-
son(X,P),parent(Y,P).
granddaughter(X,Y):-
daughter(X,P),parent(Y,P).
aunt(X,Y):-
female(X),sister(X,P),parent(P,Y).
aunt(X,Y):-
wife(X,P),sibling(P,Q),parent(Q,Y).
uncle(X,Y):-
male(X),brother(X,P),parent(P,Y).
uncle(X,Y):-
husband(X,P),sibling(P,Q),parent(Q,Y).
niece(X,Y):-
daughter(X,P),sibling(P,Y).
niece(X,Y):-
daughter(X,P),sibling(P,Q),spouse(Q,Y).
nephew(X,Y):-
son(X,P),sibling(P,Y).
nephew(X,Y):-
son(X,P),sibling(P,Q),spouse(Q,Y).
cousin(X,Y):-
parent(P,X),sibling(P,Q),parent(Q,Y).
OUTPUT: