AI NEW Lab Manual-R22 BATCH-CSE
AI NEW Lab Manual-R22 BATCH-CSE
VISVESVARAYA
COLLEGE OF ENGINEERING AND TECHNOLOGY
LABORATORY MANUAL
&
III-B.TECH-2nd SEM
Department of CSE 1
lOMoARcPSD|39 351231
VISION
To emerge as the best among the institutes of technology and research in the country dedicated to
the cause of promoting quality technical education.
MISSION
Empowerment of women engineers and technocrats with emphasis on academic excellence, life
skills and human values.
VISION
MISSION
M1: To impart skills through various learning methodologies and value-added courses to be
technically competent.
M2: To build the research culture through participations in innovative projects and publications
M3: To inculcate ethics, leadership skills, life skills and lifelong learning
M4: To expose the students to real time environment by internships and mentorships through
collaborations with industries and premier institutions.
lOMoARcPSD|39 351231
Department of CSE 3
lOMoARcPSD|39 351231
PEO-1: Adapt emerging technologies to contribute to the technical innovations for the progressive
development in their respective fields.
PEO-2: Productively engage in multidisciplinary research areas by applying the basic principles
of engineering sciences.
PEO-3: Demonstrate strong technical skills to bring out novel designs/products to address social
& environmental issues.
PSO 1: Ability to apply learned skills to build optimized solutions pertaining to Computer &
Communication Systems, Data Processing and Artificial Intelligence.
PSO 2: Employ standard strategies and practices in project development using FOSS (Free Open-
Source Software)
Department of CSE 4
lOMoARcPSD|39 351231
Course Outcomes:
CO-PO Mapping:
CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
C326.1 3 3 2 3 3
C326.2 3 3 3 3 3 2 3 3
C326.3 3 3 3 3 3 2 3 3
C326.4 3 3 3 3 3 2 3 3
Department of CSE 5
lOMoARcPSD|39 351231
CONTENTS
S. No Contents Page No
1 Objectives
2 Syllabus
3 Lab Cycles
4 Instructions to students
5 Program Development Environment
6 Programs
7 Other Programs
8 Viva Questions with Solutions
Department of CSE 6
lOMoARcPSD|39 351231
OBJECTIVES
Department of CSE 7
lOMoARcPSD|39 351231
SYLLABUS
INSTRUCTIONS TO STUDENTS
1. On entering the lab, you should make an entry in the log book available with the details
regarding student name, roll no, system no and signature.
2. You must bring Observation notebook for every lab session. Observation book should be
duly signed by your faculty, failing which your report will not be graded. You must
complete all experimental programs allotted during the session.
3. You should shut down the system properly and leave the lab neat and tidy.
GRADING :
The overall lab examination is for 100 marks. In those 75 marks for External
examination at the endof the year and remaining 25 marks will be awarded for the
internal examinations and Continuous evaluation.
Lab internal examination will carry 10 marks and Continuous evaluation will carry
remaining 15marks for each experiment.
In Continuous evaluation:
A. Experimentation 5 marks
C. Record 5 marks
Department of CSE 10
Program Development Environment
In today’s world, a computer is used to solve various types of problems, because it takes very less
time as compared to a human being.
The following steps are performed while solving a problem:
Course Objectives:
Become familiar with basic principles of AI toward problem solving, knowledge representation, and
learning.
Course Outcomes:
Apply basic principles of AI in solutions that require problem solving, knowledge representation, and
learning.
LIST OF EXPERIMENTS
TEXT BOOK:
1. Artificial Intelligence a Modern Approach, Third Edition, Stuart Russell and Peter Norvig,
Pearson Education.
REFERENCE BOOKS:
# Input Graph
graph = {
'A' : ['B','C'],
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
}
# To store visited nodes.
visitedNodes = []
# To store nodes in queue
queueNodes = []
# function
def bfs(visitedNodes, graph, snode):
visitedNodes.append(snode)
queueNodes.append(snode)
print()
print("RESULT :")
while queueNodes:
s = queueNodes.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visitedNodes:
visitedNodes.append(neighbour)
queueNodes.append(neighbour)
# Main Code
snode = input("Enter Starting Node(A, B, C, D, or E) :").upper()
# calling bfs function
bfs(visitedNodes, graph, snode)
Output:
Sample Output 1:
-------------------
Enter Starting Node(A, B, C, D, or E) :A
RESULT :
ABCDE
------------------------------------------------------------------
Sample Output 2:
-------------------
Enter Starting Node(A, B, C, D, or E) :B
RESULT :
BACDE
# Input Graph
graph = {
'A' : ['B','C'],
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
}
2. Write a Program to Implement Depth First Search Problem using Python.
visitedNodes = list()
# function
def dfs(visitedNodes, graph, node):
if node not in visitedNodes:
print (node,end=" ")
visitedNodes.append(node)
for neighbour in graph[node]:
dfs(visitedNodes, graph, neighbour)
# Driver Code
snode = input("Enter Starting Node(A, B, C, D, or E) :").upper()
# calling bfs function
print("RESULT :")
print("-"*20)
dfs(visitedNodes, graph, snode)
Output:
Sample Output 1:
------------------------------------------------------------------
Sample Output 2:
def game(player):
# diplay current mesh
print("\n", " | ".join(mesh[:3]))
print("---+---+---")
print("", " | ".join(mesh[3:6]))
print("---+---+---")
print("", " | ".join(mesh[6:]))
player1 = "X"
player2 = "O"
player = player1
mesh = list("123456789")
for i in range(9):
won = game(player)
if won:
print("\n", " | ".join(mesh[:3]))
print("---+---+---")
print("", " | ".join(mesh[3:6]))
print("---+---+---")
print("", " | ".join(mesh[6:]))
print(f"*** Player {player} won! ***")
break
player = player1 if player == player2 else player2
else:
# 9 moves without a win is a draw.
print("Game ends in a draw.")
Output:
Sample Output:
1|2|3
---+---+---
4|5|6
---+---+---
7|8|9
Enter player X's choice : 5
1|2|3
---+---+---
4|X|6
---+---+---
7|8|9
Enter player O's choice : 3
1|2|O
---+---+---
4|X|6
---+---+---
7|8|9
Enter player X's choice : 1
X|2|O
---+---+---
4|X|6
---+---+---
7|8|9
Enter player O's choice : 6
X|2|O
---+---+---
4|X|O
---+---+---
7|8|9
Enter player X's choice : 9
X|2|O
---+---+---
4|X|O
---+---+---
7|8|X
*** Player X won! ***
4. Write a Program to Implement 8-Puzzle game Problem using Python.
def bfs(start_state):
target = [1, 2, 3, 4, 5, 6, 7, 8 , 0]
dq = deque([start_state])
visited = {tuple(start_state): None}
while dq:
state = dq.popleft()
if state == target:
path = []
while state:
path.append(state)
state = visited[tuple(state)]
return path[::-1]
zero = state.index(0)
row, col = divmod(zero, 3)
for move in (-3, 3, -1, 1):
new_row, new_col = divmod(zero + move, 3)
if 0 <= new_row < 3 and 0 <= new_col < 3 and abs(row - new_row) + abs(col - new_col) ==
1:
neighbor = state[:]
neighbor[zero], neighbor[zero + move] = neighbor[zero + move], neighbor[zero]
if tuple(neighbor) not in visited:
visited[tuple(neighbor)] = state
dq.append(neighbor)
def printSolution(path):
for state in path:
print("\n".join(' '.join(map(str, state[i:i+3])) for i in range(0, 9, 3)), end="\n-----\n")
# Example Usage
startState = [1, 3, 0 , 6, 8, 4, 7, 5, 2]
solution = bfs(startState)
if solution:
printSolution(solution)
print(f"Solved in {len(solution) - 1} moves.")
else:
print("No solution found.")
Output:
130
684
752
-----
134
680
752
-----
134
682
750
-----
134
682
705
-----
.
.
.
-----
123
450
786
-----
123
456
780
-----
Solved in 20 moves.
5. Write a Program to Implement Water-Jug Game Problem using Python.
print("Steps: ")
print("Jug1 \t Jug2 ")
print("----- \t ------")
waterJug(0, 0)
Output:
Steps:
Jug1 Jug2
----- ------
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2
Solution Found
6. Write a Program to Implement Travelling Salesman Problem using Python.
def tsp_bfs(graph):
print("Path Traversal:")
while dq:
cur_path, cur_cost = dq.popleft()
cur_city = cur_path[-1]
print("\nOptimal Solution:")
print(f"Minimum cost: {min_cost}")
print(f"Optimal path: {opt_path}")
Output:
Path Traversal:
Current Path: [0], Current Cost: 0
Current Path: [0, 1], Current Cost: 10
Current Path: [0, 2], Current Cost: 15
Current Path: [0, 3], Current Cost: 20
Current Path: [0, 1, 2], Current Cost: 45
Current Path: [0, 1, 3], Current Cost: 35
Current Path: [0, 2, 1], Current Cost: 50
Current Path: [0, 2, 3], Current Cost: 45
Current Path: [0, 3, 1], Current Cost: 45
Current Path: [0, 3, 2], Current Cost: 50
Current Path: [0, 1, 2, 3], Current Cost: 75
Current Path: [0, 1, 3, 2], Current Cost: 65
Current Path: [0, 2, 1, 3], Current Cost: 75
Current Path: [0, 2, 3, 1], Current Cost: 70
Current Path: [0, 3, 1, 2], Current Cost: 80
Current Path: [0, 3, 2, 1], Current Cost: 85
Optimal Solution:
Minimum cost: 80
Optimal path: [0, 1, 3, 2, 0]
7. Write a Program to Implement Tower of Hanoi Problem using Python.
"""
num (int): Number of disks.
source (str): The name of the source tower.
aux (str): The name of the auxiliary tower.
target (str): The name of the target tower.
"""
if num == 1:
print(f"Move disk 1 from {source} to {target}")
return
# Move num-1 disks from source to auxiliary
tower_of_hanoi(num - 1, source, target, aux)
print(f"Move disk {num} from {source} to {target}")
# Move the num-1 disks from auxiliary to target
tower_of_hanoi(num - 1, aux, source, target)
Output:
# Example usage
num_disks = 3
tower_of_hanoi(num_disks, "A", "B", "C")
def monkey_banana_problem():
# Initial state
initial_state = ('Far-Chair', 'Chair-Not-Under-Banana', 'Off-Chair', 'Empty') # (Monkey's
Location, Monkey's Position on Chair, Chair's Location, Monkey's Status)
print(f"\n Initial state is {initial_state}")
goal_state = ('Near-Chair', 'Chair-Under-Banana', 'On-Chair', 'Holding') # The goal state when
the monkey has the banana
while dq:
current_state, actions_taken = dq.popleft()
Output:
Initial state is ('Far-Chair', 'Chair-Not-Under-Banana', 'Off-Chair', 'Empty')
Solution Found!
Actions to achieve goal:
Action: Move to Chair, Resulting State: ('Near-Chair', 'Chair-Not-Under-Banana', 'Off-Chair',
'Empty')
Action: Push Chair under Banana, Resulting State: ('Near-Chair', 'Chair-Under-Banana', 'Off-
Chair', 'Empty')
Action: Climb Chair, Resulting State: ('Near-Chair', 'Chair-Under-Banana', 'On-Chair', 'Empty')
Action: Grasp Banana, Resulting State: ('Near-Chair', 'Chair-Under-Banana', 'On-Chair', 'Holding')
Final State: ('Near-Chair', 'Chair-Under-Banana', 'On-Chair', 'Holding')
9. Write a Program to Implement Alpha- Beta Problem using Python.
-------------------
depth (int): Current depth in the game tree.
node_index (int): Index of the current node in the values array.
maximizing_player (bool): True if the current player is maximizing, False otherwise.
values (list): List of leaf node values.
alpha (float): Best value for the maximizing player.
beta (float): Best value for the minimizing player.
Returns:
int: The optimal value for the current player.
"""
import math
if maximizing_player:
max_eval = -math.inf
for i in range(2): # Each node has two children
eval = alpha_beta_pruning(depth - 1, node_index * 2 + i, False, values, alpha, beta)
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break # Beta cutoff
return max_eval
else:
min_eval = math.inf
for i in range(2): # Each node has two children
eval = alpha_beta_pruning(depth - 1, node_index * 2 + i, True, values, alpha, beta)
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break # Alpha cutoff
return min_eval
# Example usage
if __name__ == "__main__":
# Leaf node values for a complete binary tree
values = [3, 5, 6, 9, 1, 2, 0, -1]
depth = 3 # Height of the tree
optimal_value = alpha_beta_pruning(depth, 0, True, values, -math.inf, math.inf)
print(f"The optimal value is: {optimal_value}")
Output:
The optimal value is: 5
10. Write a Program to Implement 8-Queens Problem using Python.
def printSolution(board):
"""Print the chessboard configuration."""
for row in board:
print(" ".join("Q" if col else "." for col in row))
print("\n")
return True
result = False
for col in range(n):
if isSafe(board, row, col, n):
# Place the queen
board[row][col] = 1
# Recur to place the rest of the queens
result = solveNQueens(board, row + 1, n) or result
# Backtrack
board[row][col] = 0
return result
def nQueens(n):
"""Driver function to solve the N-Queens problem."""
board = [[0] * n for _ in range(n)]
if not solveNQueens(board, 0, n):
print("No solution exists.")
else:
print("Solutions printed above.")
Output:
# Solve the 8-Queens problem
nQueens(8)
Q.......
....Q...
.......Q
.....Q..
..Q.....
......Q.
.Q......
...Q....
Q.......
.....Q..
.......Q
..Q.....
......Q.
...Q....
.Q......
....Q...
.
.
.......Q
...Q....
Q.......
..Q.....
.....Q..
.Q......
......Q.
....Q...