AI Journal
AI Journal
PYTHON CODE:-
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
OUTPUT:-
PYTHON CODE:-
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
OUTPUT:-
Practical No : 2
A) Write a program to simulate 4-Queen / N-Queen problem
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end = " ")
print()
return True
if isSafe(board, i, col):
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# Driver Code
solveNQ()
OUTPUT:-
NOTE:
1. The user is prompted to enter n where n is the number of queens to place and
the size of the board.
2. Solve queens is called on n to display all possible board configurations and the
number of solutions.
B) Write a program to solve tower of Hanoi problem
PYTHON CODE:-
def moveTower(height, fp,tp,wp):
if height >=1:
moveTower(height-1,fp,wp,tp)
print("Moving disk from ", fp, " to ",tp)
moveTower(height-1,wp,tp,fp)
moveTower(3,"A","B","C")
OUTPUT:-
Practical No : 3
PYTHON CODE:-
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
def children(branch, depth, alpha, beta):
global tree
global root
global pruned
i=0
for child in branch:
if type(child) is list:
(nalpha, nbeta) = children(child, depth + 1, alpha, beta)
if depth % 2 == 1:
beta = nalpha if nalpha < beta else beta
else:
alpha = nbeta if nbeta > alpha else alpha
branch[i] = alpha if depth % 2 == 0 else beta
i += 1
else:
if depth % 2 == 0 and alpha < child:
alpha = child
if depth % 2 == 1 and beta > child:
beta = child
if alpha >= beta:
pruned += 1
break
if depth == root:
tree = alpha if root == 0 else beta
return (alpha, beta)
alphabeta(None)
OUTPUT:-
B) Write a program for Hill climbing problem
increment = 0.1
startingPoint = [1, 1]
point1 = [1,5]
point2 = [6,4]
point3 = [5,2]
point4 = [2,1]
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
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
#print i,' ', round(startingPoint[0], 2), round(startingPoint[1], 2)
i+=1
else:
flag = False
OUTPUT:-
Practical No : 4
A) Write a program to implement A* algorithm
PYTHON CODE:-
#Install the below given libraries via pip
#pip install simpleai
#pip install pydot flask
from simpleai.search import SearchProblem, astar
class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
else:
return []
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
OUTPUT:-
Practical No : 5
A) Write a program to solve water jug problem
PYTHON CODE:-
def pour(jug1, jug2):
max1, max2, fill = 5, 7, 4 #Change maximum capacity and final capacity
print(jug1, "\t",jug2)
if jug2 is fill:
return
elif jug2 is max2:
pour(0, jug1)
elif jug1 != 0 and jug2 == 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:-
B) Design the simulation of tic – tac – toe game using min-max algorithm
AIM:- Design the simulation of tic – tac – toe game using min-max algorithm
PYTHON CODE:-
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):
"""
: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 = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append([x, y])
return cells
if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]
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 start_game():
"""
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()
start_game()
OUTPUT:-
Practical No : 6
A) Write a program to solve Missionaries and Cannibals problem
AIM:-
PYTHON CODE:-
#Python program to illustrate Missionaries & cannibals Problem
#This code is contributed by Sunit Mal
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 than
missionaries then the cannibals would eat the missionaries\n3. The boat cannot cross the river
by itself with no people on board")
lM = 3 #lM = Left side Missionaries number
lC = 3 #lC = Laft side Cannibals number
rM=0 #rM = Right side Missionaries number
rC=0 #rC = Right side cannibals number
userM = 0 #userM = User input for number of missionaries for right to left side
travel
userC = 0 #userC = User input for number of cannibals for right to left travel
k=0
print("\nM M M C C C | --- | \n")
try:
while(True):
while(True):
print("Left side -> right side river travel")
#uM = user input for number of missionaries for left to right travel
#uC = user input for number of cannibals for left to right travel
uM = int(input("Enter number of Missionaries travel => "))
uC = int(input("Enter number of Cannibals 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
except EOFError as e:
print("\nInvalid input please retry !!")
OUTPUT:-
B) Design an application to simulate number puzzle problem
PYTHON CODE:-
# Python3 program to print the path from root
# node to destination node for N*N-1 puzzle
# algorithm using Branch and Bound
# The solution assumes that instance of
# puzzle is solvable
# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []
# Node structure
class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):
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
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
if isSafe(new_tile_pos[0], new_tile_pos[1]):
# Driver Code
# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
Practical No : 7
A) Write a program to shuffle Deck of cards
PYTHON CODE:-
import random
deck=[]
suits=["S", "D","C","H"]
ranks= ['2','3','4','5','6','7','8','9','10','J', 'Q', 'K', 'A']
PYTHON CODE:-
from sys import maxsize
from itertools import permutations
V=4
for i in next_permutation:
#print("prem", i)
# store current Path weight(cost)
current_pathweight = 0
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
OUTPUT:-
Practical No : 8
A) Solve the block of World problem
PYTHON CODE:-
tab = []
result = []
goalList = ["a", "b", "c", "d", "e"]
def parSolution(N):
for i in range(N):
if goalList[i] != result[i]:
return False
return True
def Ontab(problem):
# check if everything in stack is on the tab
if len(problem) != 0:
tab.append(problem.pop())
Ontab(problem)
# if everything is on the tab the we return true
else:
return True
def goal_stack_planing(problem):
# pop problem and put in tab
Ontab(problem)
# print index and number of blocks on result stack
if Onblock(0, 1):
print(result)
if __name__ == "__main__":
problem = ["c", "a", "e", "d", "b"]
print("Goal Problem")
for k, j in zip(goalList, problem):
print(k+" "+j)
goal_stack_planing(problem)
print("result Solution")
print(result)
OUTPUT:-
PYTHON CODE:-
#Install the below given libraries via pip
#pip install simpleai
constraints = [
(('WA', 'NT'), const_different),
(('WA', 'SA'), const_different),
(('SA', 'NT'), const_different),
(('SA', 'Q'), const_different),
(('NT', 'Q'), const_different),
(('SA', 'NSW'), const_different),
(('Q', 'NSW'), const_different),
(('SA', 'V'), const_different),
(('NSW', 'V'), const_different),
]
print(backtrack(my_problem))
print(backtrack(my_problem, variable_heuristic=MOST_CONSTRAINED_VARIABLE))
print(backtrack(my_problem, variable_heuristic=HIGHEST_DEGREE_VARIABLE))
print(backtrack(my_problem, value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem, variable_heuristic=MOST_CONSTRAINED_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem, variable_heuristic=HIGHEST_DEGREE_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(min_conflicts(my_problem))
OUTPUT:-
Practical No : 9
A) Derive the expressions based on Associative law.
Practical No : 10
A) Write a program to derive the predicate (for eg: Sachin is batsman, batsman is
cricketer => Sachin is cricketer)
Code:
batsman (sachin)
batsman (msd)
batman (virat)
baller (anilkumble)
baller (harbhajan)
cricketer (x) :- baller(x)
cricketer (x) :- batsman(x)
Output:-
1 ?- baller (x)
x = anilkumble
3 ?- batsman (virat)
true
4 ?- baller (virat).
False
B) Write a program which contains three predicates: male, female, parent. Make
rules for following family relations: father, mother, grandfather grandmother
brother, uncle, sister, aunt, nephew & niece, cousin.
Question:
1 Draw family tree.
2 Define: Classes, facts, predicates and rules with conjunction and disjunction.
2: clauses
A prolog program consists of no. of clauses. Each clause is either fact or rule. After a prolog program is
consulted (on loaded). VIN prolog interpreter, users can submit goals or queries, of prolog interpreter
will give result (answers) according to facts and rules.
Facts
A fact must start with a predicate (which is an atom) and end with a full stop. The predicate may be
followed by one or more arguments which are enclosed by parenthesis . The argument can be atoms
(in this case, these atoms are treated as constants), numbers, variables or lists. Arguments are
separated by commas. If we consider the argument in a fact to be objects, then the predicate of the fact
describes a property of an object. In a prolog program, a presence of a fact indicated a statement that
is true. An absence of a fact indicates a statement that is not true.
Predicates
In addition to self-defined predefines, prolog also provides built-in predicates. The following are some
common built-in predicates:
Rules:
A rule can be viewed as an extension of a fact with added conditions that also have to be satisfied for it
to be true. It consists of two parts, the first part is similar to fact (a predicate with arguments). The
second part consists of other clauses (fact or rules are separated by commas). which must all be true
for the true itself to be true. these two parts are separated by “:-“. You may interpret this operator as
"if" in English. The comma "," Express conjunction is Prolog. The semicolon ":" Expresses disjunction
in Prolog.
Python Code:
male (ramjibhai)
male (dhirubhai)
male (pravinbhai)
male (hitesh)
male (harsh)
female (shantiben)
female (hansaben)
female (bhartiben)
female (krishna)
female (harshita)
parent (ramjibhai, dhirubhai)
parent (ramjibhai, pravinbhai)
parent (shantiben, dhirubhai)
parent (shantiben, pravinbhai)
parent (dhirubhai, hitesh).parent (dhisubhai, krishna)
parent (hansaben, hitesh).parent (hansaben, krishna)
parent (bhartiben, harsh).parent (bhartiben, harshita)
father (x,y): -male (x), partent (x,y)
mother (x,y):- female(x), parent (x,y)
sister (x,y):- female(x), father (z,x), father (z,y), x\=y
brother (x,y):-male(x), father (z,x), father (z,y), x\=y
cousin (x,y) :- father (z, x), father (w,y), brother(z,w)
grandma (x,y):- father (z,y), mother (x,z)
grandpa (x,y):- father (z,y), father (x,z)
uncle(x,y):- father (z,y), brother (x,z)
aunt (x,y) :- uncle (z,y), father (z,q), mother(x,q)
nephew (x,y):- male (x), father (z,x), brother (y,z)
niece (x, y) :-female (x), father (z,x), brother (y,z)
Output:
? - mother (y,hitesh)
y = hansaben
? - sister(x,hitesh)
x = krishna
? brother(x,hitesh)
False