AI LAB MANUAL (2)
AI LAB MANUAL (2)
CSE
1
Programs to Implement the following using Python
3. Tic-Tac-Toe game
4. 8-Puzzle problem
5. Water-Jug problem
7. Tower of Hanoi
9. Alpha-Beta Pruning
2
1.Write a Program to implement Breadth First
Input Graph
SOURCE CODE :
# Input Graph
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
visitedNodes = []
queueNodes = []
# function
visitedNodes.append(snode)
3
queueNodes.append(snode)
print()
print("RESULT :")
while queueNodes:
s = queueNodes.pop(0)
visitedNodes.append(neighbour)
queueNodes.append(neighbour)
# Main Code
OUTPUT :
Sample Output 1:
-------------------
RESULT :
ABCDE
------------------------------------------------------------------
Sample Output 2:
-------------------
RESULT : BACDE
4
1. Write a Program to implement Depth First
Input Graph
SOURCE 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)
5
OUTPUT :
Sample Output 1:
RESULT : A B C E D
------------------------------------------------------------------
Sample Output 2:
RESULT :B A C E D
SOURCE CODE :
win_positions = (
6
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.")
7
OUTPUT :
Sample Output:
1|2|3
---+---+---
4|5|6
---+---+---
7|8|9
1|2|3
---+---+---
4|X|6
---+---+---
7|8|9
1|2|O
---+---+---
4|X|6
---+---+---
7|8|9
X|2|O
8
---+---+---
4|X|6
---+---+---
7|8|9
X|2|O
---+---+---
4|X|O
---+---+---
7|8|9
X|2|O
---+---+---
4|X|O
---+---+---
7|8|X
9
3. Write a Program to Implement 8-Puzzle
SOURCE CODE :
def bfs(start_state):
target = [1, 2, 3, 4, 5, 6, 7, 8 , 0]
dq = deque([start_state])
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)
neighbor = state[:]
10
neighbor[zero], neighbor[zero + move] = neighbor[zero + mov
e], neighbor[zero]
visited[tuple(neighbor)] = state
dq.append(neighbor)
def printSolution(path):
# Example Usage
startState = [1, 3, 0 , 6, 8, 4, 7, 5, 2]
solution = bfs(startState)
if solution:
printSolution(solution)
else:
OUTPUT :
1 3 0
6 8 4
7 5 2
-----
1 3 4
6 8 0
7 5 2
11
-----
1 3 4
6 8 2
7 5 0
-----
1 3 4
6 8 2
7 0 5
-----
-----
1 2 3
4 5 0
7 8 6
-----
1 2 3
4 5 6
7 8 0
-----
Solved in 20 moves.
12
4. Write a Program to Implement Water-Jug
SOURCE CODE :
print(vol1,"\t", vol2)
print("Solution Found")
return True
if visited[vol1][vol2]:
return False
visited[vol1][vol2] = True
print(vol1,"\t", vol2)
return (
13
waterJug(0, vol2) or # Empty jug1
print("Steps: ")
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
14
5. Write a Program to Implement Travelling
SOURCE CODE :
def tsp_bfs(graph):
dq = deque([([startCity], 0)])
print("Path Traversal:")
while dq:
cur_city = cur_path[-1]
15
if total_cost < min_cost:
min_cost = total_cost
continue
dq.append((new_path, new_cost))
graph = [
print("\nOptimal Solution:")
16
6. Write a Program to Implement Tower of Hanoi
using Python.
def tower_of_hanoi(num, source, aux, target):
"""
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)
# Example usage
num_disks = 3
tower_of_hanoi(num_disks, "A", "B", "C")
OUTPUT :
17
7. Write a Program to Implement Monkey
SOURCE CODE :
def monkey_banana_problem():
# Initial state
actions = {
18
}
visited = set()
while dq:
if current_state == goal_state:
print("\nSolution Found!")
print(action)
return
if current_state in visited:
continue
visited.add(current_state)
next_state = action_func(current_state)
19
if next_state and (next_state not in visited):
monkey_banana_problem()
OUTPUT :
Solution Found!
20
9.Write a Program to Implement Alpha-Beta
Pruning using Python.
SOURCE CODE :
"""
-------------------
Returns:
"""import math
return values[node_index]
21
if maximizing_player:
max_eval = -math.inf
return max_eval
else:
min_eval = math.inf
return min_eval
22
OUTPUT :
SOURCE CODE :
def printSolution(board):
print("\n")
# Check column
for i in range(row):
if board[i][col]:
return False
i, j = row, col
if board[i][j]:
return False
23
i -= 1
j -= 1
i, j = row, col
if board[i][j]:
return False
i -= 1
j += 1
return True
if row == n:
printSolution(board)
return True
result = False
board[row][col] = 1
# Backtrack
24
board[row][col] = 0
return result
def nQueens(n):
else:
nQueens(8)
OUTPUT :
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
. . . Q . . . .
Q . . . . . . .
25
. . . . . Q . .
. . . . . . . Q
. . Q . . . . .
. . . . . . Q .
. . . Q . . . .
. Q . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . Q . . . .
Q . . . . . . .
. . Q . . . . .
. . . . . Q . .
. Q . . . . . .
. . . . . . Q .
. . . . Q . . .
26
27