III-II AI Lab Manual R22
III-II AI Lab Manual R22
To empower students with professional education using creative & innovative technical
practices of global competence and research aptitude to become competitive engineers
with ethical values and entrepreneurial skills
To impart value based professional education through creative and innovative teaching-
learning process to face the global challenges of the new era technology.
Vision:
To achieve value oriented and quality education with excellent standards on par with evolving
technologies and produce technocrats of global standards with capabilities of facing futuristic
challenges.
Mission:
To enrich advanced knowledge among students for reinforcing the domain knowledge and
develop capabilities and skills to solve complex engineering problems.
To impart value based professional education for a challenging career in Computer Science and
Engineering.
To transform the graduates for contributing to the socio-economic development and welfare of the
society through value-based education
PEO1: To acquire logical and analytical skills in core areas of Computer Science & Information
Technology.
PEO2: To adapt new technologies for the changing needs of IT industry through self-study,
graduate work and professional development.
PEO3: To demonstrate professional and ethical attitude, soft skills, team spirit, leadership skills
and execute assignments to the perfection.
Program Specific Outcomes:
PSO1: Software Development: Ability to grasp the software development life cycle of software
systems and possess competent skill and knowledge of software design process.
PSO2: Industrial Skills Ability: Ability to interpret fundamental concepts and methodology of
computer systems so that students can understand the functionality of hardware and software
aspects of computer systems.
PSO3: Ethical and Social Responsibility: Communicate effectively in both verbal and written
form, will have knowledge of professional and ethical responsibilities and will show the
understanding of impact of engineering solutions on the society and also will be aware of
contemporary issues.
Program Outcomes:
PO2: Problem Analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences and Engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts and demonstrate the knowledge of, and need for
sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and Team Work: Function effectively as an individual and as a member or leader
in diverse teams and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as being able to comprehend and write
effective reports and design documentation, make effective presentations and give and receive
clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering management principles and apply these to one's own work, as a member and leader in
a team to manage projects and in multidisciplinary environments.
PO12: Life-Long Learning: Recognize the need for and have the preparation and ability to engage
in independent and lifelong learning in the broadest context of technological change.
COURSE OBJECTIVES
COURSE OUTCOMES
AIM: The main aim of Breadth-First Search (BFS) in Artificial Intelligence (AI) is to
systematically explore all possible states of a problem in a level-wise manner to find the optimal
solution (if one exists).
CODE:
# 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)
6
OUTPUT:
RESULT :
ABCDE
RESULT :
BACDE
7
EXPERIMENT NO: 2. Write a Program to implement Depth First Search (DFS) using
Python.
AIM: The primary aim of Depth-First Search (DFS) in Artificial Intelligence (AI) is to
systematically explore a problem space by expanding the deepest unexplored node first before
backtracking when necessary.
DESCRIPTION: DFS is a graph traversal algorithm that explores as far as possible along each
branch before backtracking. It uses a stack (either explicit or via recursion) to keep track of
nodes.
CODE:
# Input Graph
graph = {
'A' : ['B','C'],
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
}
# Set used to store visited nodes.
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:
Enter Starting Node(A, B, C, D, or E) :A
RESULT :
--------------------
ABCED
AIM: T h e a i m o f t h e T i c - T a c - T o e p r o b l e m i s t o d e v e l o p a n a l g o r i t h m t h a t
allows two players (or a player and an AI) to take turns marking spaces in a
3×3 grid, following the game’s rules, and determine the winner or detect a
draw.
DESCRIPTION: Tic-Tac-Toe is a two-player strategy game played on a 3×3 grid. The players
take turns marking the grid with either "X" or "O", aiming to be the first to form a straight line of
three marks either horizontally, vertically, or diagonally. If the grid is filled without any player
achieving this, the game results in a draw.
CODE
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:
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
10
Enter player X's choice : 1
X|2|O
---+---+---
4|X|6
---+---+---
7|8|9
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! ***
11
EXPERIMENT NO: 4 Write a Program to Implement 8-Puzzle problem using Python.
AIM: The 8-Puzzle Problem is a sliding puzzle that consists of a 3×3 grid with eight numbered tiles
(1 to 8) and one blank space. The goal is to move the tiles in a sequence to reach a desired goal state
DESCRIPTION: The 8-puzzle problem is a classic AI problem that involves a 3×3 grid with eight
numbered tiles (1-8) and one empty space. The objective is to move the tiles by sliding them into the
empty space to reach a desired goal state from a given initial configuration.
CODE:
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")
12
# 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.
13
EXPERIMENT N O : 5. Write a Program to Implement Water-Jug problem using Python
AIM: The aim of the Water Jug Problem is to measure a specific quantity of water using two jugs
of different capacities
DESCRIPTION: The Water Jug Problem is a classic AI problem that involves two jugs of
different capacities and the goal of measuring a specific amount of water using them.
Given two jugs with capacities X liters and Y liters (without any measurement markings), and an
unlimited water supply, determine how to obtain exactly Z liters of water using the following
operations:
1. Fill a jug completely.
2. Empty a jug completely.
3. Transfer water from one jug to another until the first is empty or the second is full.
CODE:
14
waterJug(vol1 + min(vol2, (jug1 - vol1)), vol2 - min(vol2, (jug1 - vol1))) or
# Pour water from jug2 to jug1
waterJug(vol1 - min(vol1, (jug2 - vol2)), vol2 + min(vol1, (jug2 - vol2)))
# Pour water from jug1 to jug2
)
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
15
EXPERIMENT NO: 6. Write a Program to Implement Travelling Salesman Problem using
Python.
AIM: The aim of the Travelling Salesman Problem (TSP) is to find the shortest possible route that
allows a salesman to visit each city exactly once and return to the starting point while minimizing
the total travel distance or cost.
CODE:
def tsp_bfs(graph):
n = len(graph) # Number of cities
startCity = 0 # Starting city
min_cost = float('inf') # Initialize minimum cost as infinity
opt_path = [] # To store the optimal path
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]
17
EXPERIMENT NO: 7. Write a Program to Implement Tower of Hanoi using Python.
AIM: The aim of the Tower of Hanoi is to transfer a given number of disks from a source peg to a
destination peg using an auxiliary peg
DESCRIPTION: The Tower of Hanoi is a mathematical puzzle that consists of three rods and N
disks of different sizes, stacked in decreasing order on one rod. The objective is to move all disks
from the source rod to the destination rod using an auxiliary rod
CODE:
# Example usage
num_disks = 3
tower_of_hanoi(num_disks, "A", "B", "C")
OUTPUT:
18
EXPERIMENT NO: 8 Write a Program to Implement Monkey Banana Problem using
Python.
AIM: The goal is to enable a monkey to reach and grab a bunch of bananas hanging from the
ceiling by using available objects (like a box) in a structured way.
DESCRIPTION: The Monkey and Banana Problem is a classic AI problem in state space search
and planning. It involves a monkey in a room with a bunch of bananas hanging from the ceiling.
The monkey cannot reach the bananas directly but can use a movable box to climb and grab them.
CODE:
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:
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')
20
EXPERIMENT NO: 9 Write a Program to Implement Alpha-Beta Pruning using Python.
AIM: The aim of Alpha-Beta Pruning is to improve the efficiency of the Minimax algorithm used in
decision-making and game-playing AI (e.g., Chess, Tic-Tac-Toe). It reduces the number of nodes evaluated
in the search tree without affecting the final decision.
DESCRIPTION:
In game-playing AI (like chess or tic-tac-toe), the Minimax algorithm is used to find the best
possible move.Alpha-Beta pruning optimizes Minimax by eliminating unnecessary branches in the
game tree. It skips evaluating moves that won’t influence the final decision, reducing the number of
nodes searched and improving efficiency.
CODE
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:
21
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:
22
EXPERIMENT NO: 10. Write a Program to Implement 8-Queens Problem using Python.
AIM: The aim of the 8-puzzle problem is to rearrange a given set of numbered tiles (1 to 8) on a
3×3 grid by moving them into the correct order using the blank space. The objective is to reach the
goal state from an initial scrambled configuration by moving tiles into the empty space using the
least number of moves.
DESCRIPTION:
The 8 Queens Problem is a classic combinatorial problem in which the goal is to place eight queens
on an 8×8 chessboard such that no two queens attack each other. This means:
No two queens should be in the same row.
No two queens should be in the same column.
No two queens should be on the same diagonal.
CODE:
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
23
def solveNQueens(board, row, n):
"""Use backtracking to solve the N-Queens problem."""
if row == n:
printSolution(board)
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:
Q.......
....Q...
.......Q
.....Q..
..Q.....
......Q.
.Q......
...Q....
24