19CS413 LabManual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

LAB MANUAL

19CS413 – ARTIFICIAL INTELLIGENCE LABORATORY (R-


2019)
(COMMON TO CSE & ECE)

1
Department of Computer Science and Engineering

19CS413 – ARTIFICIAL INTELLIGENCE LABORATORY (R-2019)


(COMMON TO CSE & ECE)

List of Experiments

1. Implementation of Breadth First Search.


2. Implementation of Depth First Search.
3. Implementation of A* Search.
4. Implementation of Minimax Search.
5. Implementation of Alpha Beta Pruning.
6. Implementation of Tic-Tac Game using Minimax Search.
7. Simple Logic Programming using Prolog – Factorial of number / Towers of Hanoi.
8. Implementation of Block World Problem / Monkey Banana Problem using PDDL.
9. Implementation of Medical Diagnosis Expert System.
10. Implementation of Computer Maintenance Expert System.

Faculty-In Charge HOD

2
Ex.No: 1 Implementation of Breadth First Search

AIM :

To write a python program to implement Breadth first Search.

ALGORIHM:

Step1: Start the program

Step 2: Create the graph by using adjacency list representation

Step 3: Define a function bfs and take the set “visited” is empty and “queue” is empty
Step 4: Search start with initial node and add the node to visited and queue.
Step 5: For each neighbor node, check node is not in visited then add node to visited and queue list.
Step 6: Creating loop to print the visited node.
Step 7: Call the bfs function by passing arguments visited, graph and starting node.
Step 8: Stop the program.

3
PROGRAM:
#breadth first Search in python
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Output:

Result:

Thus the python program is used to found the breadth first search order for the
4
Ex.No: 2 Implementation of Depth First Search

given graph and output was verified successfully.

AIM :

To write a python program to implement Depth first Search.

ALGORIHM:

Step1: Start the program

Step 2: Create the graph by using adjacency list representation

Step 3: Define a function dfs and take the set “visited” is empty
Step 4: Search start with initial node. Check the node is not visited then print the node.
Step 5: For each neighbor node, recursively invoke the dfs search.
Step 6: Call the dfs function by passing arguments visited, graph and starting node.
Step 8: Stop the program.

5
PROGRAM:
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Output:

Result:
Thus the python program is used to found the search order of Depth first search for
the given graph and output was verified successfully

6
Ex.No: 3 Implementation of A* Search

AIM :

To write a python program to implement A* Search.

ALGORIHM:

Step1: Start the program

Step 2: Create a Class Graph. Initialize graph as directed or undirected by using constructor.

Step 3: Define a function make_undirected for creating undirected graph by adding symmetric
edges.Define a function connect for
Step 4: Search start with initial node. Check the node is not visited then print the node.
Step 5: For each neighbor node, recursively invoke the dfs search.
Step 6: Call the dfs function by passing arguments visited, graph and starting node.
Step 8: Stop the program.

PROGRAM:
class Graph:
# Initialize the class
def __init__(self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
# Create an undirected graph by adding symmetric edges
def make_undirected(self):
for a in list(self.graph_dict.keys()):
for (b, dist) in self.graph_dict[a].items():
self.graph_dict.setdefault(b, {})[a] = dist
# Add a link from A and B of given distance, and also add the inverse link if the
graph is undirected
def connect(self, A, B, distance=1):
self.graph_dict.setdefault(A, {})[B] = distance
if not self.directed:
self.graph_dict.setdefault(B, {})[A] = distance
# Get neighbors or a neighbor
def get(self, a, b=None):
links = self.graph_dict.setdefault(a, {})
if b is None:
return links
else:
return links.get(b)
7
# Return a list of nodes in the graph
def nodes(self):
s1 = set([k for k in self.graph_dict.keys()])
s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])
nodes = s1.union(s2)
return list(nodes)
# This class represent a node
class Node:
# Initialize the class
def __init__(self, name:str, parent:str):
self.name = name
self.parent = parent
self.g = 0 # Distance to start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
# Compare nodes
def __eq__(self, other):
return self.name == other.name
# Sort nodes
def __lt__(self, other):
return self.f < other.f
# Print node
def __repr__(self):
return ('({0},{1})'.format(self.name, self.f))
# A* search
def astar_search(graph, heuristics, start, end):

# Create lists for open nodes and closed nodes


open = []
closed = []
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
open.append(start_node)

# Loop until the open list is empty


while len(open) > 0:
# Sort the open list to get the node with the lowest cost first
open.sort()
# Get the node with the lowest cost
current_node = open.pop(0)
# Add the current node to the closed list
closed.append(current_node)

# Check if we have reached the goal, return the path


if current_node == goal_node:
path = []
while current_node != start_node:
path.append(current_node.name + ': ' + str(current_node.g))
current_node = current_node.parent
8
path.append(start_node.name + ': ' + str(start_node.g))
# Return reversed path
return path[::-1]
# Get neighbours
neighbors = graph.get(current_node.name)
# Loop neighbors
for key, value in neighbors.items():
# Create a neighbor node
neighbor = Node(key, current_node)
# Check if the neighbor is in the closed list
if(neighbor in closed):
continue
# Calculate full path cost
neighbor.g = current_node.g + graph.get(current_node.name,
neighbor.name)
neighbor.h = heuristics.get(neighbor.name)
neighbor.f = neighbor.g + neighbor.h
# Check if neighbor is in open list and if it has a lower f value
if(add_to_open(open, neighbor) == True):
# Everything is green, add neighbor to open list
open.append(neighbor)
# Return None, no path is found
return None
# Check if a neighbor should be added to open list
def add_to_open(open, neighbor):
for node in open:
if (neighbor == node and neighbor.f > node.f):
return False
return True
# The main entry point for this module
def main():
# Create a graph
graph = Graph()
# Create graph connections (Actual distance)
graph.connect('Frankfurt', 'Wurzburg', 111)
graph.connect('Frankfurt', 'Mannheim', 85)
graph.connect('Wurzburg', 'Nurnberg', 104)
graph.connect('Wurzburg', 'Stuttgart', 140)
graph.connect('Wurzburg', 'Ulm', 183)
graph.connect('Mannheim', 'Nurnberg', 230)
graph.connect('Mannheim', 'Karlsruhe', 67)
graph.connect('Karlsruhe', 'Basel', 191)
graph.connect('Karlsruhe', 'Stuttgart', 64)
graph.connect('Nurnberg', 'Ulm', 171)
graph.connect('Nurnberg', 'Munchen', 170)
graph.connect('Nurnberg', 'Passau', 220)
graph.connect('Stuttgart', 'Ulm', 107)
graph.connect('Basel', 'Bern', 91)
graph.connect('Basel', 'Zurich', 85)
graph.connect('Bern', 'Zurich', 120)
graph.connect('Zurich', 'Memmingen', 184)
9
graph.connect('Memmingen', 'Ulm', 55)
graph.connect('Memmingen', 'Munchen', 115)
graph.connect('Munchen', 'Ulm', 123)
graph.connect('Munchen', 'Passau', 189)
graph.connect('Munchen', 'Rosenheim', 59)
graph.connect('Rosenheim', 'Salzburg', 81)
graph.connect('Passau', 'Linz', 102)
graph.connect('Salzburg', 'Linz', 126)
# Make graph undirected, create symmetric connections
graph.make_undirected()
# Create heuristics (straight-line distance, air-travel distance)
heuristics = {}
heuristics['Basel'] = 204
heuristics['Bern'] = 247
heuristics['Frankfurt'] = 215
heuristics['Karlsruhe'] = 137
heuristics['Linz'] = 318
heuristics['Mannheim'] = 164
heuristics['Munchen'] = 120
heuristics['Memmingen'] = 47
heuristics['Nurnberg'] = 132
heuristics['Passau'] = 257
heuristics['Rosenheim'] = 168
heuristics['Stuttgart'] = 75
heuristics['Salzburg'] = 236
heuristics['Wurzburg'] = 153
heuristics['Zurich'] = 157
heuristics['Ulm'] = 0
# Run the search algorithm
path = astar_search(graph, heuristics, 'Frankfurt', 'Ulm')
print(path)
print()
# Tell python to run main method
if __name__ == "__main__": main()
Output:

Result:

Thus the python program is used to found the shortest path for the given graph using A*
algorithm and output was verified successfully.
10
Ex.No: 4 Implementation of Minimax Sear
Search
Date :

AIM:

Write a mini-max search algorithm to find the optimal value of MAX Player from the given
graph.

ALGORITHM:
STEP 1: Start the program
STEP 2: import the math package
STEP 3: Specify the score value of leaf nodes and find the depth of binary tree from leaf
nodes.
STEP 4: Define the minimax function
STEP 5: If maximum depth is reached then get the score value of leaf node.
STEP 6: Max player find the maximum value by calling the minmax function recursively.
STEP 7: Min player find the minimum value by calling the minmax function recursively.
STEP 8: Call the minimax function and print the optimum value of Max player.
STEP 9: Stop the program.

PROGRAM:

import math
def minimax (curDepth, nodeIndex,
maxTurn, scores,
targetDepth):
# base case : targetDepth reached
if (curDepth == targetDepth):
return scores[nodeIndex]
if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
False, scores, targetDepth))

else:
return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
True, scores, targetDepth))

# Driver code
scores = [3, 5, 2, 9, 12, 5, 23, 20]
treeDepth = math.log(len(scores), 2) # calculate depth of node log 8 (base 2) = 3)
print("The optimal value is : ", end = "")
print(minimax(0, 0, True, scores, treeDepth))

11
OUTPUT

RESULT :
Thus the optimum value of max player was found using minimax search.

12
Ex.No: 5 Implementation of Alpha Beta Pruning

AIM:

Write a Alpha beta pruning algorithm to find the optimal value of MAX Player from the
given graph.

ALGORITHM:
STEP 1: Start the program
STEP 2: Initially assign MAX and MIN value as 1000 and -1000.
STEP 3: Define the minimax function using alpha beta pruning
STEP 4: If maximum depth is reached then return the score value of leaf node. [depth taken
as 3]
STEP 5: In Max player turn, assign the alpha value by finding the maximum value by calling
the minmax function recursively.
STEP 6: In Min player turn, assign beta value by finding the minimum value by calling the
minmax function recursively.
STEP 7: Specify the score value of leaf nodes and Call the minimax function.
STEP 8: Print the best value of Max player.
STEP 9: Stop the program.

PROGRAM:

# Python program to demonstrate working of Alpha-Beta Pruning

# Initial values of Alpha and Beta


MAX, MIN = 1000, -1000

# Returns optimal value for current player


#(Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
values, alpha, beta):

# Terminating condition. i.e


# leaf node is reached
if depth == 3:
return values[nodeIndex]

if maximizingPlayer:

best = MIN

# Recur for left and right children


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)
13
# Alpha Beta Pruning
if beta <= alpha:
break

return best

else:
best = MAX

# Recur for left and


# right children
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)

# Alpha Beta Pruning


if beta <= alpha:
break

return best

# Driver Code
if __name__ == "__main__":
values = [3, 5, 6, 9, 1, 2, 0, -1]

OUTPUT:

RESULT :

Thus the best score of max player was found using Alpha Beta Pruning.

14
Ex.No: 6 Implementation of Tic-Tac Game using Minimax Search

AIM:

To solve a Tic-Tac Toe game using minimax search.

ALGORITHM:
STEP 1: Start the program
STEP 2: Define the function printBoard() to print the 3*3 board positions of Tic-Tac-Toe
game.
STEP 3:Define the function spaceIsFree() to check the board position is empty or not.
STEP 4: Define the function checkForWin() to check the winning board position of player
on same row or same column or same diagonal.
STEP 5: Define the function checkWhichMarkWon () to check the board position is filled by
given player on same row or same column or same diagonal.
STEP 6: Define the mini-max function for getting the best score value of board position. if
computer win then return -1 else if player win then return 1 otherwise return 0 for draw.
STEP 7: Call the function

PROGRAM:

def printBoard(board):
print(board[1] + '|' + board[2] + '|' + board[3])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[7] + '|' + board[8] + '|' + board[9])
print("\n")

def spaceIsFree(position):
if board[position] == ' ':
return True
else:
return False

def insertLetter(letter, position):


if spaceIsFree(position):
board[position] = letter
printBoard(board)
if (checkDraw()):
print("Draw!")
exit()
if checkForWin():
if letter == 'X':
print("Bot wins!")
exit()
15
else:
print("Player wins!")
exit()

return
else:
print("Can't insert there!")
position = int(input("Please enter new position: "))
insertLetter(letter, position)
return

def checkForWin():
if (board[1] == board[2] and board[1] == board[3] and board[1] != ' '):
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] != ' '):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] != ' '):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] != ' '):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] != ' '):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] != ' '):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] != ' '):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] != ' '):
return True
else:
return False

def checkWhichMarkWon(mark):
if board[1] == board[2] and board[1] == board[3] and board[1] == mark:
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] == mark):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] == mark):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] == mark):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] == mark):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] == mark):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] == mark):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] == mark):
return True
else:
16
return False

def checkDraw():
for key in board.keys():
if (board[key] == ' '):
return False
return True

def playerMove():
position = int(input("Enter the position for 'O': "))
insertLetter(player, position)
return

def compMove():
bestScore = -800
bestMove = 0
for key in board.keys():
if (board[key] == ' '):
board[key] = bot
score = minimax(board, 0, False)
board[key] = ' '
if (score > bestScore):
bestScore = score
bestMove = key

insertLetter(bot, bestMove)
return

def minimax(board, depth, isMaximizing):


if (checkWhichMarkWon(bot)):
return 1
elif (checkWhichMarkWon(player)):
return -1
elif (checkDraw()):
return 0

if (isMaximizing):
bestScore = -800
for key in board.keys():
if (board[key] == ' '):
board[key] = bot
score = minimax(board, depth + 1, False)
board[key] = ' '
if (score > bestScore):
bestScore = score
return bestScore

17
else:
bestScore = 800
for key in board.keys():
if (board[key] == ' '):
board[key] = player
score = minimax(board, depth + 1, True)
board[key] = ' '
if (score < bestScore):
bestScore = score
return bestScore

board = {1: ' ', 2: ' ', 3: ' ',


4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}

printBoard(board)
print("Computer goes first! Good luck.")
print("Positions are as follow:")
print("1, 2, 3 ")
print("4, 5, 6 ")
print("7, 8, 9 ")
print("\n")
player = 'O'
bot = 'X'

global firstComputerMove
firstComputerMove = True
while not checkForWin():
compMove()

18
OUTPUT:

19
20
21
RESULT:
Thus the tic-tac-toe game was implemented successfully using minimax search.

22
Ex.No: 7 Logic Programming – Factorial of number

AIM:

To write a logic program for finding the factorial of given number using SWI-PROLOG.

ALGORITHM:

STEP 1: Start the program

STEP 2: Write a rules for finding factorial of given program in SWI-PROLOG.


a) factorial of 0 is 1 => written as factorial(0,1).
b) factorial of number greater than 0 obtained by recursively calling the factorial
function.

STEP 3: Run the program to find answer of query.

STEP 4: Stop the program.

PROGRAM :

file name : factorial.pl

factorial(0,1).
factorial(A,B) :-
A > 0,
C is A-1,
factorial(C,D),
B is A*D.

OUTPUT:

23
RESULT:
Thus the factorial of given number was found by logic programming

24
Ex.No: 8 Logic Programming – Towers of Hanoi

AIM:

To write a logic program to solve Towers of Hanoi problem using SWI-PROLOG.

ALGORITHM:

STEP 1: Start the program

STEP 2: Write a rules for finding solution of Towers of Hanoi in SWI-PROLOG.


a) If only one disk => Move disk from X to Y.
b) If Number of disk greater than 0 then
i) Move N-1 disks from X to Z.
ii) Move Nth disk from X to Y
iii) Move N-1 disks from Y to X.

STEP 3: Run the program to find answer of query.

STEP 4: Stop the program.

PROGRAM :

file name : towersofhanoi.pl

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).

25
OUTPUT:

RESULT:
Thus the solution of Towers of Hanoi problem was found by logic programming.

26
Ex.No: 9 Implementation of Block World Problem using PDDL

AIM:
To find the sequence of plan for Block word problem using PDDL

ALGORITHM:

Step 1 : Start the program


Step 2 : Create a domain for Block world Problem
Step 3 : Create a domain by specifying predicates clear, on table, on, arm-empty, holding.
Step 4 : Specify the actions pickup, putdown, stack and un-stack in Block world problem
Step 5 : In pickup action, Robot arm pick the block on table. Precondition is Block is on table and no
other block on specified block and arm-hand empty.
Step 6: In putdown action, Robot arm place the block on table. Precondition is robot-arm holding the
block.
Step 7 : In un-stack action, Robot arm pick the block on some block. Precondition is Block is on
another block and no other block on specified block and arm-hand empty.
Step 8 : In stack action, Robot arm place the block on under block. Precondition is Block holded by
robot arm and no other block on under block.
Step 9 : Define a problem for block world problem
Step 10 : Obtain the plan for given problem

PROGRAM:

domain.pddl

(define (domain blocksworld)


(:requirements :strips :equality)
(:predicates (clear ?x)
(on-table ?x)
(arm-empty)
(holding ?x)
(on ?x ?y))
(:action pickup
:parameters (?ob)
:precondition (and (clear ?ob) (on-table ?ob) (arm-empty))
:effect (and (holding ?ob) (not (clear ?ob)) (not (on-table ?ob))
(not (arm-empty))))
(:action putdown
:parameters (?ob)
:precondition (and (holding ?ob))
:effect (and (clear ?ob) (arm-empty) (on-table ?ob)
(not (holding ?ob))))
(:action stack
:parameters (?ob ?underob)
:precondition (and (clear ?underob) (holding ?ob))
:effect (and (arm-empty) (clear ?ob) (on ?ob ?underob)
(not (clear ?underob)) (not (holding ?ob))))
(:action unstack
:parameters (?ob ?underob)
:precondition (and (on ?ob ?underob) (clear ?ob) (arm-empty))
27
:effect (and (holding ?ob) (clear ?underob)
(not (on ?ob ?underob)) (not (clear ?ob)) (not (arm-empty)))))
Problem 1: Problem.pddl

(define (problem pb1)


(:domain blocksworld)
(:objects a b)
(:init (on-table a) (on-table b) (clear a) (clear b) (arm-empty))
(:goal (and (on a b))))

OUTPUT:

Problem 2: Problem2.pddl
(define(problem pb3)
(:domain blocksworld)
(:objects a b c)
(:init (on-table a) (on-table b) (on-table c)
(clear a) (clear b) (clear c) (arm-empty))
(:goal (and (on a b) (on b c))))

OUTPUT:

RESULT : Thus the plan for given block world problem is obtained by PDDL editor or STRIPS FIDDLE
using domain description.

28
Ex.No: 10 Implementation of Monkey Banana Problem using PDDL

AIM :

To find the sequence of plan for Monkey Banana problem using PDDL description

ALGORITHM :
Step 1: Start the program
Step 2 : Create a domain for Monkey Banana Problem
Step 3: Create a domain by specifying predicates.
Step 4: Specify the actions GOTO, CLIMB, PUSH-BOX, GET-KNIFE, GRAB-BANANAS in Monkey
Banana problem
Step 5: Define a problem for Monkey Banana problem.
Step 6: Obtain the plan for given problem
Step 7: Stop the program

PROGRAM
Domain.pddl
(define (domain monkey)
(:requirements :strips)
(:constants monkey box knife bananas glass waterfountain)
(:predicates (location ?x)
(on-floor)
(at ?m ?x)
(hasknife)
(onbox ?x)
(hasbananas)
(hasglass)
(haswater))
;; movement and climbing
(:action GO-TO
:parameters (?x ?y)
:precondition (and (location ?x) (location ?y) (on-floor) (at monkey ?y))
:effect (and (at monkey ?x) (not (at monkey ?y))))
(:action CLIMB
:parameters (?x)
:precondition (and (location ?x) (at box ?x) (at monkey ?x))
:effect (and (onbox ?x) (not (on-floor))))
(:action PUSH-BOX
:parameters (?x ?y)
:precondition (and (location ?x) (location ?y) (at box ?y) (at monkey ?y)
(on-floor))
:effect (and (at monkey ?x) (not (at monkey ?y))
(at box ?x) (not (at box ?y))))
;; getting bananas
(:action GET-KNIFE
:parameters (?y)
:precondition (and (location ?y) (at knife ?y) (at monkey ?y))
:effect (and (hasknife) (not (at knife ?y))))
(:action GRAB-BANANAS
:parameters (?y)
:precondition (and (location ?y) (hasknife)
(at bananas ?y) (onbox ?y))
29
:effect (hasbananas))
;; getting water
(:action PICKGLASS
:parameters (?y)
:precondition (and (location ?y) (at glass ?y) (at monkey ?y))
:effect (and (hasglass) (not (at glass ?y))))
(:action GETWATER
:parameters (?y)
:precondition (and (location ?y) (hasglass)
(at waterfountain ?y)
(at monkey ?y)
(onbox ?y))
:effect (haswater)))

Problem :
(define (problem pb1)
(:domain monkey)
(:objects p1 p2 p3 p4 bananas monkey box knife)
(:init (location p1)
(location p2)
(location p3)
(location p4)
(at monkey p1)
(on-floor)
(at box p2)
(at bananas p3)
(at knife p4)
)
(:goal (and (hasbananas)))
)

OUTPUT:

RESULT :

Thus the plan was found for Monkey banana problem using PDDL editor.

30
Ex.No: 11 Logic Programming – Medical Diagnosis Expert System

AIM :

Write a Prolog program to build a medical Diagnosis Expert System.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Write the rules for each diseases.
STEP 3: If patient have mumps then symptoms are fever and swollen glands.
STEP 4: If patient have cough, sneeze and running nose then disease is measles.
STEP 5: if patien have symptoms headache ,sneezing ,sore_throat, runny_nose and chills
then disease is common cold.
STEP 6: Define rules for all disease.
STEP 7:Call the go predicates.
STEP 8: Collect the symptoms of Patient and give the hypothesis of disease.

PROGRAM :

domains
disease,indication = symbol
Patient,name = string

predicates
hypothesis(string,disease)
symptom(name,indication)
response(char)
go
clauses
go :-
write("What is the patient's name? "),
readln(Patient),
hypothesis(Patient,Disease),
write(Patient,"probably has ",Disease,"."),nl.

go :-
write("Sorry, I don't seem to be able to"),nl,
write("diagnose the disease."),nl.

symptom(Patient,fever) :-
write("Does ",Patient," have a fever (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,rash) :-
write("Does ",Patient," have a rash (y/n) ?"),
31
response(Reply),
Reply='y'.

symptom(Patient,headache) :-
write("Does ",Patient," have a headache (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,runny_nose) :-
write("Does ",Patient," have a runny_nose (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,conjunctivitis) :-
write("Does ",Patient," have a conjunctivitis (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,cough) :-
write("Does ",Patient," have a cough (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,body_ache) :-
write("Does ",Patient," have a body_ache (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,chills) :-
write("Does ",Patient," have a chills (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,sore_throat) :-
write("Does ",Patient," have a sore_throat (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,sneezing) :-
write("Does ",Patient," have a sneezing (y/n) ?"),
response(Reply),
Reply='y'.

symptom(Patient,swollen_glands) :-
write("Does ",Patient," have a swollen_glands (y/n) ?"),
response(Reply),
Reply='y'.

hypothesis(Patient,measles) :-
symptom(Patient,fever),
symptom(Patient,cough),
32
symptom(Patient,conjunctivitis),
symptom(Patient,runny_nose),
symptom(Patient,rash).

hypothesis(Patient,german_measles) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,runny_nose),
symptom(Patient,rash).

hypothesis(Patient,flu) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,body_ache),
symptom(Patient,conjunctivitis),
symptom(Patient,chills),
symptom(Patient,sore_throat),
symptom(Patient,runny_nose),
symptom(Patient,cough).

hypothesis(Patient,common_cold) :-
symptom(Patient,headache),
symptom(Patient,sneezing),
symptom(Patient,sore_throat),
symptom(Patient,runny_nose),
symptom(Patient,chills).
hypothesis(Patient,mumps) :-
symptom(Patient,fever),
symptom(Patient,swollen_glands).
hypothesis(Patient,chicken_pox) :-
symptom(Patient,fever),
symptom(Patient,chills),
symptom(Patient,body_ache),
symptom(Patient,rash).
hypothesis(Patient,measles) :-
symptom(Patient,cough),
symptom(Patient,sneezing),
symptom(Patient,runny_nose).
response(Reply) :-
readchar(Reply),
write(Reply),nl.

33
OUTPUT:

RESULT :
Thus the medical diagnosis expert system was designed using Logic programming.

34
Ex.No: 12 Computer Maintenance Expert System

AIM :

Write a program to develop a computer Maintenance Expert System .

PROGRAM
main :-
retractall(asked(_,_)),
fault(Problem),
!,
nl,
write('The problem is '), write(Problem), write(.), nl.
main :-
nl,
write('The problem cannot be recognized.'), nl.

problem(disc_format) :-
query('Does the computer show error cannot format').

problem(boot_failure) :-
query('Does the computer show boot failure').

problem(bad_sector) :-
query('Does the computer show bad sector error').

problem(cannot_read) :-
query('Does the computer show cannot read from specified device').

problem(long_beep) :-
query('Is there a long beep during bootup').

problem(short_beep) :-
query('Is there a short beep during bootup').

problem(two_long_beeps) :-
query('Are there two long beeps during bootup').

problem(two_short_beeps) :-
query('Are there two short beeps during bootup').

problem(blank_display) :-
query('Is there a blank display during bootup').

problem(repeating_short_beeps) :-
query('Are there repeating short beeps during bootup').

35
problem(continuous_beeps) :-
query('Is there a continuous beep during bootup').

problem(no_beep) :-
query('Is there a beep during bootup').

problem(not_printing) :-
query('Is there a problem with printing').

problem(missing_dots) :-
query('Is there a missing character during printing').

problem(non_uniform_printing) :-
query('Is there uniform printing').

problem(spread_ink) :-
query('Is there spreading of ink during printing').

problem(paper_jam) :-
query('Is there a paper jam during printing').

problem(out_of_paper) :-
query('Is there out-of- paper error during printing').

fault(power_supply) :-
problem(repeating_short_beeps),
problem(continuous_beeps),
problem(blank_display),
problem(no_beep).

fault(display_adapter) :-
problem(long_beep),
problem(two_short_beeps),
problem(blank_display),
problem(no_beep).

fault(motherboard) :-
problem(long_beep),
problem(short_beep).

fault(hard_disc) :-
problem(two_short_beeps),
problem(blank_display).

fault(booting_problem) :-
problem(bad_sector),
problem(boot_failure).

fault(floppy_disk_unusable) :-
problem(bad_sector),
problem(cannot_read),
36
problem(disc_format).

fault(printer_head) :-
problem(not_printing),
problem(missing_dots),
problem(nonuniform_printing).

fault(ribbon) :-
problem(not_printing),
problem(missing_dots),
problem(spread_ink).

fault(paper) :-
problem(not_printing),
problem(paper_jam),
problem(out_of_paper).

query(Prompt) :-
( asked(Prompt, Reply) -> true
; nl, write(Prompt), write(' (y/n)? '), flush,
read_line_to_codes(user_input, [Initial|_]),
( [Initial] = "y" -> Reply = y
; [Initial] = "Y" -> Reply = y
; Reply = n
),
assert(asked(Prompt, Reply))
),
Reply = y.

OUTPUT:

RESULT:

Thus the computer maintenance expert system was developed using Prolog and Python.
37
Ex.No: 13 SIMPLE LOGICAL PROOF USING PROLOG

AIM :

To write a prolog program to find the answer of query.

ALGORIHM:

Step1: Start the program

Step 2: Convert the sentence into First order Logic

Step 3: Convert the sentence into Horn clause form


Step 4: Add rules and predicates in a program
Step 5: Pass the query to program.
Step 6: Prolog interpreter shows the output and return answer.
Step 8: Stop the program.
PROGRAMS :

1. Construct the FOL representation for the following sentences


1. John likes all kinds of food.
2. Apples are food.
3. Chicken is a food.
4. Sue eats everything Bill eats.
5. Bill eats peanuts
Convert into clause form and Prove that John like Apple by using Prolog.

PROGRAM :
likes(john,X):-

food(X).

eats(bill,X):-

eats(sue,X).

eats(Y,X):-

food(X).

eats(bill,peanuts).

food(apple).

food(chicken).

food(peanuts).
38
OUTPUT :

2. Consider the following facts and represent them in predicate form:


 Steve likes easy courses
 Science courses are hard
 All the courses in Have fun department are easy
 BK301 is Have fun department course.
Convert the facts in predicate form to clauses and then prove by resolution: “Steve likes BK301
course”

Program:

likes(steve,X):-
easycourse(X).
hard(sciencecourse).
easycourse(X):-
course(X,dept(havefun)).
course(bk301,dept(havefun)).

OUTPUT:

39
3. Consider the statement
“This is a crime for an American to sell weapons to hostile nations. The Nano , enemy of America has some
missiles and its missiles were sold it by Colonal West who is an American”

Convert to Clause form and prove west is criminal by using Prolog.

Program:

criminal(X):-
american(X),
weapon(Y),
hostile(Z),
sells(X,Y,Z).
weapon(Y):-
missile(Y).
hostile(Z):-
enemy(Z,X).

sells(west,Y,nano):-
missile(Y),
owns(nano,Y).

missile(m).
owns(nano,m).
enemy(nano,america).
american(west).

RESULT :
Thus the prolog programs were executed successfully and the answer of query was found.

40
Ex.No: 14 ANIMAL QUIZ USING PYTHON

AIM :
To develop a simple animal quiz program using python.

ALGORIHM:
Step1: Start the program

Step 2: Define the score as zero initially.

Step 3: Create a function to check the answer and update the score.
Step 4: Ask the questions to user and call the function.
Step 5: Print the score value at the end of program
Step 6: Stop the program.

PROGRAM

def check_guess(guess,answer):
global score
if guess.lower() == answer.lower():
print("Coreect answer")
score=score+1;

score=0
print('Guess the Animal!')
guess1=input('Which bear lives at the North Pole?')
check_guess(guess1,'polar bear')
guess2=input('Which is the fastest land animal?')
check_guess(guess2,'cheetah')
guess1=input('Which is the largest animal?')
check_guess(guess1,'blue whale')
print('Your Score is' + str(score))

41
OUTPUT:

RESULT:

Thus the python program was created for Animal Quiz and was implemented successfully.

42

You might also like