Professional Documents
Culture Documents
19CS413 LabManual
19CS413 LabManual
19CS413 LabManual
ENGINEERING
LAB MANUAL
1
Department of Computer Science and Engineering
List of Experiments
2
Ex.No: 1 Implementation of Breadth First Search
AIM :
ALGORIHM:
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
# 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
AIM :
ALGORIHM:
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' : []
}
# 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 :
ALGORIHM:
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):
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:
if maximizingPlayer:
best = MIN
return best
else:
best = MAX
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:
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
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
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
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:
PROGRAM :
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:
ALGORITHM:
PROGRAM :
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:
PROGRAM:
domain.pddl
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 :
ALGORITHM:
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 :
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 :
ALGORIHM:
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 :
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”
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 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