Ai Practical Journal
Ai Practical Journal
Ai Practical Journal
Output:
Practical no-2
graph={
"A":['B','C'],
"B":['A','D','E'],
"C":['A','F'],
"D":['B'],
"E":['B'],
"F":['C']
}
start_vertex=’A’
bfs(graph,start_vertex)
Output:
Practical no-3
Code:
Output:
Practical no-4
Output:
Practical no-5
Code:
footballer(ronaldo).
batsman(rohit).
keeper(msdhoni).
bowler(bhumra).
cricketer(X) :-batsman(X);keeper(X);bowler(X).
Output:
Practical no-6
Write a program to solve tower of Hanoi problem ?
Code:
%TOWER OF HANOI
move(1,X,Y,_):-
write('move top disk from'),
write(X),
write(' to '),
write(Y),nl.
move(N,X,Y,Z):-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
Ouput:
Practical no-7
Derive the expression based on associative law ?
Code:
%define associative law for adittion
associative_law(A,B,C,Result):-Result is A*(B*C).
expression1(2,3,7). %expression
expression2(5,6,7).
%drive the results using law
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 expression2 using associative
law:'),write(Result2),nl.
Output:
Practical no-8
Derive the expression based on distributive law ?
Code:
Output:
Practical no-10B
Write a program which contains three
predicate:male,female,parent make rules for following family
relation:father,mother,grandfather,grandmother etc
Family tree.
Code:
female(koyal).
female(bulbul).
female(sonu).
female(rohini).
parent(popatlal,tapu). %popatlal is parent of tapu.
parent(popatlal,bulbul). %popatlal is parent of bulbul.
parent(koyal,tapu).
parent(koyal, bulbul).
parent(tapu,sumit).
parent(sonu,sumit).
parent(bulbul,rohini).
parent(raman,rohini).
mother(X,Y):-parent(X,Y),female(X).
father(X,Y):-parent(X,Y),male(X).
grandfather(X,Z):-father(X,Y),parent(Y,Z).
grandmother(X,Z):-mother(X,Y),parent(Y,Z).
Output:
Practical no-8B
Solve constraint satisfaction problem ?
Code:
coloring(MH,GO,AP,GJ,RJ,HR,MP):-
different(MH,GO),
different(MH,AP),
different(MH,GJ),
different(MH,MP),
different(GJ,RJ),
different(RJ,HR),
different(GO,AP).
different(red,blue).
different(blue,red).
different(blue,green).
different(green,blue).
different(green,red).
different(red,green).
Output:
Practical no-2A
Write a program to simulate 4-queen/n-queen problem ?
Code:
#Number of queens
print ("Enter the number of queens")
N = int(input())
#chessboard
#NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
def N_queen(n):
#if n is 0, solution found
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
'''checking if we can place a queen here or not
queen will not be placed if the place is being attacked
or already occupied'''
if (not(is_attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
#recursion
#wether we can put the next queen with this arrangment or not
if N_queen(n-1)==True:
return True
board[i][j] = 0
return False
N_queen(N)
for i in board:
print (i)
Output:
Practical no-5A
Write a program to solve water jug problem ?
Code:
from collections import defaultdict
jug1, jug2, aim = 4, 3, 2
visited = defaultdict(lambda: False)
def waterJugSolver(amt1, amt2):
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1-amt1)),
amt2 - min(amt2, (jug1-amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2-amt2)),
amt2 + min(amt1, (jug2-amt2))))
else:
return False
print("Steps: ")
waterJugSolver(0, 0)
Output:
Practical no-5B
Design the simulation of tic-tac-toe game using min-max
algorithm ?
Code:
#!/usr/bin/env python3
from math import inf as infinity
from random import choice
import platform
import time
from os import system
HUMAN = -1
COMP = +1
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]
def evaluate(state):
"""
Function to heuristic evaluation of state.
:param state: the state of the current board
:return: +1 if the computer wins; -1 if the human wins; 0 draw
"""
if wins(state, COMP):
score = +1
elif wins(state, HUMAN):
score = -1
else:
score = 0
return score
def game_over(state):
"""
This function test if the human or computer wins
:param state: the state of the current board
:return: True if the human or computer wins
"""
return wins(state, HUMAN) or wins(state, COMP)
def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
return cells
if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]
for cell in empty_cells(state):
x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
state[x][y] = 0
score[0], score[1] = x, y
if player == COMP:
if score[2] > best[2]:
best = score # max value
else:
if score[2] < best[2]:
best = score # min value
return best
def clean():
"""
Clears the console
"""
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
chars = {
-1: h_choice,
+1: c_choice,
0: ' '
}
str_line = '---------------'
print('\n' + str_line)
for row in state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |', end='')
print('\n' + str_line)
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
if depth == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
else:
move = minimax(board, depth, COMP)
x, y = move[0], move[1]
set_move(x, y, COMP)
time.sleep(1)
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
if not can_move:
print('Bad move')
move = -1
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')
def main():
"""
Main function that calls all functions
"""
clean()
h_choice = '' # X or O
c_choice = '' # X or O
first = '' # if human is the first
human_turn(c_choice, h_choice)
ai_turn(c_choice, h_choice)
exit()
if _name_ == '_main_':
main()
Output:
Practical no-6A
Write a program to solve missionaries and cannibals problem
Code:
print("\n")
print("\tGame Start\nNow the task is to move all of them to right side of the river")
print("rules:\n1. The boat can carry at most two people\n2. If cannibals num greater then
missionaries then the cannibals would eat the missionaries\n3. The boat cannot cross the river by
itself with no people on board")
lM = 3
lC = 3
rM=0
rC=0
userM = 0
userC = 0
k=0
print("\nM M M C C C | --- | \n")
try:
while(True):
while(True):
print("Left side -> right side river travel")
if((uM==0)and(uC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((uM+uC) <= 2)and((lM-uM)>=0)and((lC-uC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM = (lM-uM)
lC = (lC-uC)
rM += uM
rC += uC
print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| --> | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")
k +=1
break
if((rM+rC) == 6):
print("You won the game : \n\tCongrats")
print("Total attempt")
print(k)
break
while(True):
print("Right side -> Left side river travel")
userM = int(input("Enter number of Missionaries travel => "))
userC = int(input("Enter number of Cannibals travel => "))
if((userM==0)and(userC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((userM+userC) <= 2)and((rM-userM)>=0)and((rC-userC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM += userM
lC += userC
rM -= userM
rC -= userC
k +=1
print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| <-- | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")
Output: