Artificial Intelligence Lab: Laboratory Report
Artificial Intelligence Lab: Laboratory Report
Submitted By
Student Name Nikita Anand
System_Id 2020468119
Programme/Section MCA
PRACTICAL LIST
Unit Practical based on goal-based problems
1
a Lab Implementation of Water Jug Problem.
expt.1
b Lab Introduction to Lisp, and basic programming in Lisp like following:
expt.2
i. Write a LISP function to compute sum of squares.
ii. Write a LISP function to compute difference of squares. (if x > y
return x2 – y2, Otherwise y2 – x2).
iii. Write a Recursive LISP function which takes one argument as a
list and return last element of the list. (Do not use last predicate.)
iv. Write a Recursive LISP function which takes one argument as a
list and return list except last element of the list. (Do not use
butlast.)
v. Write a Recursive LISP function which takes one argument as a
list and return reverse of the list. (Do not use reverse predicate).
vi. Write a Recursive LISP function which takes two arguments first
an atom second a list returns a list after removing first occurrence
of that atom within the list.
vii. Write a Recursive LISP function which appends two lists together.
viii. Write a recursive LISP function which takes 2 lists as arguments
and returns a list containing alternate elements from each list.
c Lab Advance programming in Lisp like following: (Any 3)
expt.3
i. Write a function that compute the factorial of a number.(factorial
of 0 is 1, and factorial of n is n*(n-1)*...1.Factorial is defined only
for integers greater than or equal to 0.)
ii. Write a function that evaluate a fully parenthesized infix arithmetic
expression. For examples, (infix (1+ (2*3))) should return 7.
iii. Write a function that performs a depth first traversal of binary tree.
The function should return a list containing the tree nodes in the
order they were visited.
iv. Write a LISP program for water jug problem.
v. Write a LISP program that determines whether an integer is prime.
Unit Practical related to uninformed search algorithm.
2
a, b, Lab Refer following figure as map with distance details, Write a program in
expt.4 your preferred language to generate path from ARAD to BUCHREST,
analyze result obtained by
a) Depth First Search
b) Breadth First Search
c) Uniform Cost Search
c Lab i. Write a program in your preferred language to generate steps to solve Tower of
expt.5 Hanoi problem.
ii. Write a program in your preferred language to solve n-queens problem
Unit Practical related to informed search algorithm.
3
a,b,c Lab Write a program in your preferred language to solve the 8 puzzle Problem-
expt.6
using A* algorithm.
Unit Practical related to knowledge representations and logical reasoning (Any 2)
4
A Lab Write PROLOG program to Program to categorize animal characteristics.
expt.7
B Lab Write PROLOG program to solver for the linear equation A*X + B = 0.
expt.8 Let the predicate linear (A, B, X) return the root X of the equation.
c Lab Write a PROLOG program that answers questions about family members
expt.9 and relationships includes predicates and rules which define sister, brother,
father, mother, grandchild, grandfather and uncle. The program should be
able to answer queries such as the following:
father(x, Amit)
grandson(x, y)
uncle (sumit, puneet)
mother (anita, x)
print("JUG1\tJUG2")
pour(0, 0)
OUTPUT
OUTPUT
ii. Write a LISP function to compute difference of squares. (if x > y return x 2 – y
2, Otherwise y 2 – x 2).
Program:
(defun diffsqr(x y)
(if ( > x y )
(write( - ( * x x ) ( * y y ) ))
(write( - ( * y y ) (* x x )))))
( diffsqr 2 3 )
OUTPUT
iii. Write a Recursive LISP function which takes one argument as a list and return
element of the list. (Do not use last predicate.)
Program:
(defun last_element(my_list)
(first(reverse my_list)))
(write (last_element '(p q r s)))
OUTPUT
iv. Write a Recursive LISP function which takes one argument as a list and return
list except last element of the list. (Do not use butlast.)
Program:
(defun exceptlast_element(my_list)
(reverse (cdr (reverse my_list))))
(write (exceptlast_element '(p q r s)))
OUTPUT
v. Write a Recursive LISP function which takes one argument as a list and return
reverse of the list. (Do not use reverse predicate).
Program:
(defun list-append (L1 L2)
(if (null L1) L2
(cons (first L1) (list-append (rest L1)
L2))))
(defun show-list-reverse (L)
(if (null L) nil
(list-append (show-list-reverse (rest L))
(list (first L)))))
(write (show-list-reverse '(1 2 3 4)))
OUTPUT
vi. Write a Recursive LISP function which takes two arguments first an atom second
a list returns a list after removing first occurrence of that atom within the list.
Program:
(defun remove(lst elt)
(cond((null lst)nil)
((equal(first lst)elt)(rest lst))
(elt(cons(first lst)
(remove(rest lst)elt)))))
(write(remove '(1 2 3 3 4 5)’3))
OUTPUT
vii. Write a Recursive LISP function which appends two lists together.
Program:
defun list-append (L1 L2)
(if (null L1) L2
(cons (first L1) (list-append (rest L1) L2))))
(write (list-append '(4 2) '(2 3 6)))
OUTPUT
viii. Write a recursive LISP function which takes 2 lists as arguments and returns a
list containing alternate elements from each list.
Program:
(defun alt( A B)
(cond ((and (endp A)(endp B))NIL)
((endp A) B)
((endp B) A)
(T (cons (car A) (alt B (cdr A))))))
(write(alt'(a b c d)'(1 2 3 4)))
OUTPUT
(defun fact(n)
(if ( = n 1 )
1
(* n(fact(- n 1)))))
(write (fact 4))
OUTPUT
(write( + 6 5))
OUTPUT
(setf L nil)
(incf start)
)
)
(defun prime(N)
OUTPUT
4. Refer following figure as map with distance details, Write a program in your
preferred language to generate path from ARAD to BUCHREST, analyze result
obtained by
Depth First Search
Program:
class node:
def __init__(self, name):
self.explored = 0
self.name = name
self.neighbours = {}
nodes = {}
start = 'Arad'
goal = 'Bucharest'
explored = []
frontier = []
path = []
f = open("F:\arad.txt", "r")
for line in f:
line = line.strip()
node1, node2, distance = line.split(",")
if node1 not in nodes:
nodes[node1] = node(node1)
if node2 not in nodes:
nodes[node2] = node(node2)
nodes[node1].neighbours[node2] = distance
nodes[node2].neighbours[node1] = distance
def initFrontier():
frontier.append(start)
nodes[start].parent = ''
def choosenode():
node = frontier.pop()
if testgoal(node):
print (goal)
pathcost = calpath(goal)
print ("path cost is {}".format(pathcost))
print ("path selected is {}".format(path))
exit()
return node
def calpath(cnode):
path.append(cnode)
if nodes[cnode].parent == '':
return 0
else:
cparent = nodes[cnode].parent
pathcost = calpath(cparent)+int(nodes[cnode].neighbours[cparent])
return pathcost
def testgoal(curnode):
if curnode == goal:
return True
return False
def graphsearch():
if not frontier:
print ("failure")
exit()
curnode = choosenode()
nodes[curnode].explored = 1
explored.append(curnode)
for neighbour in nodes[curnode].neighbours.keys():
if neighbour in frontier:
continue
if neighbour in explored:
continue
frontier.append(neighbour)
nodes[neighbour].parent = curnode
initFrontier()
while True:
graphsearch()
print (frontier)
OUTPUT
dict_hn={'Arad':336,'Bucharest':0,'Craiova':160,'Drobeta':242,'Eforie':161,
'Fagaras':176,'Giurgiu':77,'Hirsova':151,'Iasi':226,'Lugoj':244,
'Mehadia':241,'Neamt':234,'Oradea':380,'Pitesti':100,'Rimnicu':193,
'Sibiu':253,'Timisoara':329,'Urziceni':80,'Vaslui':199,'Zerind':374}
dict_gn=dict(
Arad=dict(Zerind=75,Timisoara=118,Sibiu=140),
Bucharest=dict(Urziceni=85,Giurgiu=90,Pitesti=101,Fagaras=211),
Craiova=dict(Drobeta=120,Pitesti=138,Rimnicu=146),
Drobeta=dict(Mehadia=75,Craiova=120),
Eforie=dict(Hirsova=86),
Fagaras=dict(Sibiu=99,Bucharest=211),
Giurgiu=dict(Bucharest=90),
Hirsova=dict(Eforie=86,Urziceni=98),
Iasi=dict(Neamt=87,Vaslui=92),
Lugoj=dict(Mehadia=70,Timisoara=111),
Mehadia=dict(Lugoj=70,Drobeta=75),
Neamt=dict(Iasi=87),
Oradea=dict(Zerind=71,Sibiu=151),
Pitesti=dict(Rimnicu=97,Bucharest=101,Craiova=138),
Rimnicu=dict(Sibiu=80,Pitesti=97,Craiova=146),
Sibiu=dict(Rimnicu=80,Fagaras=99,Arad=140,Oradea=151),
Timisoara=dict(Lugoj=111,Arad=118),
Urziceni=dict(Bucharest=85,Hirsova=98,Vaslui=142),
Vaslui=dict(Iasi=92,Urziceni=142),
Zerind=dict(Oradea=71,Arad=75)
)
import queue as Q
#from RMP import dict_hn
start='Arad'
goal='Bucharest'
result=''
main()
OUTPUT
Program:
dict_hn={'Arad':336,'Bucharest':0,'Craiova':160,'Drobeta':242,'Eforie':161,
'Fagaras':176,'Giurgiu':77,'Hirsova':151,'Iasi':226,'Lugoj':244,
'Mehadia':241,'Neamt':234,'Oradea':380,'Pitesti':100,'Rimnicu':193,
'Sibiu':253,'Timisoara':329,'Urziceni':80,'Vaslui':199,'Zerind':374}
dict_gn=dict(
Arad=dict(Zerind=75,Timisoara=118,Sibiu=140),
Bucharest=dict(Urziceni=85,Giurgiu=90,Pitesti=101,Fagaras=211),
Craiova=dict(Drobeta=120,Pitesti=138,Rimnicu=146),
Drobeta=dict(Mehadia=75,Craiova=120),
Eforie=dict(Hirsova=86),
Fagaras=dict(Sibiu=99,Bucharest=211),
Giurgiu=dict(Bucharest=90),
Hirsova=dict(Eforie=86,Urziceni=98),
Iasi=dict(Neamt=87,Vaslui=92),
Lugoj=dict(Mehadia=70,Timisoara=111),
Mehadia=dict(Lugoj=70,Drobeta=75),
Neamt=dict(Iasi=87),
Oradea=dict(Zerind=71,Sibiu=151),
Pitesti=dict(Rimnicu=97,Bucharest=101,Craiova=138),
Rimnicu=dict(Sibiu=80,Pitesti=97,Craiova=146),
Sibiu=dict(Rimnicu=80,Fagaras=99,Arad=140,Oradea=151),
Timisoara=dict(Lugoj=111,Arad=118),
Urziceni=dict(Bucharest=85,Hirsova=98,Vaslui=142),
Vaslui=dict(Iasi=92,Urziceni=142),
Zerind=dict(Oradea=71,Arad=75)
)
import queue as Q
start='Arad'
goal='Bucharest'
result=''
def get_fn(citystr):
cities=citystr.split(',')
hn=gn=0
for ctr in range(0,len(cities)-1):
gn=gn+dict_gn[cities[ctr]][cities[ctr+1]]
hn=dict_hn[cities[len(cities)-1]]
return(hn+gn)
def printout(cityq):
for i in range(0,cityq.qsize()):
print(cityq.queue[i])
def expand(cityq):
global result
tot,citystr,thiscity=cityq.get()
nexttot=999
if not cityq.empty():
nexttot,nextcitystr,nextthiscity=cityq.queue[0]
if thiscity==goal and tot<nexttot:
result=citystr+'::'+str(tot)
return
print("Expanded city------------------------------",thiscity)
print("Second best f(n)------------------------------",nexttot)
tempq=Q.PriorityQueue()
for cty in dict_gn[thiscity]:
tempq.put((get_fn(citystr+','+cty),citystr+','+cty,cty))
for ctr in range(1,3):
ctrtot,ctrcitystr,ctrthiscity=tempq.get()
if ctrtot<nexttot:
cityq.put((ctrtot,ctrcitystr,ctrthiscity))
else:
cityq.put((ctrtot,citystr,thiscity))
break
printout(cityq)
expand(cityq)
def main():
cityq=Q.PriorityQueue()
thiscity=start
cityq.put((999,"NA","NA"))
cityq.put((get_fn(start),start,thiscity))
expand(cityq)
print(result)
main()
OUTPUT
5. i. Write a program in your preferred language to generate steps to solve Tower
of Hanoi problem.
Program:
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n=4
TowerOfHanoi(n,'A','B','C')
OUTPUT
Program:
class QueenChessBoard:
def __init__(self, size):
self.size = size
self.columns = []
def get_size(self):
return self.size
def get_queens_count(self):
return len(self.columns)
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 print_all_solutions_to_n_queen(size):
board = QueenChessBoard(size)
number_of_solutions = print_all_solutions_helper(board)
print('Number of solutions:', number_of_solutions)
def print_all_solutions_helper(board):
size = board.get_size()
if size == board.get_queens_count():
board.display()
print()
return 1
number_of_solutions = 0
for column in range(size):
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
number_of_solutions += print_all_solutions_helper(board)
board.remove_in_current_row()
return number_of_solutions
n = int(input('Enter n: '))
print_all_solutions_to_n_queen(n)
OUTPUT
DIRECTIONS = {"U": [-1, 0], "D": [1, 0], "L": [0, -1], "R": [0, 1]}
END = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# unicode
left_down_angle = '\u2514'
right_down_angle = '\u2518'
right_up_angle = '\u2510'
left_up_angle = '\u250C'
middle_junction = '\u253C'
top_junction = '\u252C'
bottom_junction = '\u2534'
right_junction = '\u2524'
left_junction = '\u251C'
def print_puzzle(array):
print(first_line)
for a in range(len(array)):
for i in array[a]:
if i == 0:
print(bar, Back.RED + ' ' + Back.RESET, end=' ')
else:
print(bar, i, end=' ')
print(bar)
if a == 2:
print(last_line)
else:
print(middle_line)
class Node:
def __init__(self, current_node, previous_node, g, h, dir):
self.current_node = current_node
self.previous_node = previous_node
self.g = g
self.h = h
self.dir = dir
def f(self):
return self.g + self.h
def euclidianCost(current_state):
cost = 0
for row in range(len(current_state)):
for col in range(len(current_state[0])):
pos = get_pos(END, current_state[row][col])
cost += abs(row - pos[0]) + abs(col - pos[1])
return cost
def getAdjNode(node):
listNode = []
emptyPos = get_pos(node.current_node, 0)
return listNode
def getBestNode(openSet):
firstIter = True
def buildPath(closedSet):
node = closedSet[str(END)]
branch = list()
while node.dir:
branch.append({
'dir': node.dir,
'node': node.current_node
})
node = closedSet[str(node.previous_node)]
branch.append({
'dir': '',
'node': node.current_node
})
branch.reverse()
return branch
def main(puzzle):
open_set = {str(puzzle): Node(puzzle, puzzle, 0, euclidianCost(puzzle), "")}
closed_set = {}
while True:
test_node = getBestNode(open_set)
closed_set[str(test_node.current_node)] = test_node
if test_node.current_node == END:
return buildPath(closed_set)
adj_node = getAdjNode(test_node)
for node in adj_node:
if str(node.current_node) in closed_set.keys() or str(node.current_node) in
open_set.keys() and open_set[
str(node.current_node)].f() < node.f():
continue
open_set[str(node.current_node)] = node
del open_set[str(test_node.current_node)]
if __name__ == '__main__':
br = main([[6, 2, 8],
[4, 7, 1],
[0, 3, 5]])
──┤ UP ├──
┌───┬───┬───┐
│ 6 │ 2 │ 8 │
├───┼───┼───┤
│ 4 │ │ 1 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘
──┤ UP ├──
┌───┬───┬───┐
│ 6 │ 2 │ │
├───┼───┼───┤
│ 4 │ 1 │ 8 │
├───┼───┼───┤
│ 3 │ 7 │ 5 │
└───┴───┴───┘
──┤ UP ├──
┌───┬───┬───┐
│ 4 │ 6 │ 2 │
├───┼───┼───┤
│ 3 │ 1 │ │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘
──┤ UP ├──
┌───┬───┬───┐
│ 4 │ 6 │ │
├───┼───┼───┤
│ 3 │ 1 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘
──┤ UP ├──
┌───┬───┬───┐
│ │ 1 │ 6 │
├───┼───┼───┤
│ 4 │ 3 │ 2 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘
──┤ UP ├──
┌───┬───┬───┐
│ 1 │ 3 │ │
├───┼───┼───┤
│ 4 │ 2 │ 6 │
├───┼───┼───┤
│ 7 │ 5 │ 8 │
└───┴───┴───┘
Program:
animal(mammal,tiger,carnivore,stripes).
animal(mammal,hyena,carnivore,ugly).
animal(mammal,lion,carnivore,mane).
animal(mammal,zebra,herbivore,stripes).
animal(bird,eagle,carnivore,large).
animal(bird,sparrow,scavenger,small).
animal(reptile,snake,carnivore,long).
animal(reptile,lizard,scavenger,small).
OUTPUT
Program:
female(pam).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
parent(pam,bob).
parent(tom,bob).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
OUTPUT