AI Practicals
AI Practicals
Implement Depth First Search algorithm and Breadth First Search algorithm. Use an undirected graph
and develop a recursive algorithm for searching all the vertices of a graph or tree data structure.
from collections import deque
# Function to get the graph from user input
def get_graph_from_user():
graph = {}
num_vertices = int(input("Enter the number of vertices: "))
for _ in range(num_vertices):
vertex = input(f"Enter vertex name (e.g., A, B, C, etc.): ")
neighbors = input(f"Enter neighbors of {vertex} (comma-separated):
").split(',')
neighbors = [n.strip() for n in neighbors]
graph[vertex] = neighbors
return graph
visited.add(vertex)
print(vertex, end=' ')
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex, end=' ')
visited.add(vertex)
queue.extend(neighbor for neighbor in graph[vertex] if neighbor not
in visited)
start_vertex = input("Enter the starting vertex for DFS and BFS: ")
1
Output
2
AIPR2
Implement A Star Algorithm for any game search problem
import heapq
class Node:
def __init__(self, position, parent=None):
self.position = position
self.parent = parent
self.g = 0 # Cost from start to current node
self.h = 0 # Heuristic - estimated cost to goal
self.f = 0 # Total cost
start_node = Node(start)
end_node = Node(end)
heapq.heappush(open_list, start_node)
while open_list:
current_node = heapq.heappop(open_list)
if current_node.position == end_node.position:
path = []
while current_node:
path.append(current_node.position)
current_node = current_node.parent
return path[::-1] # Return reversed path
closed_set.add(current_node.position)
(x, y) = current_node.position
neighbors = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] # 4 directions
heapq.heappush(open_list, neighbor)
return None # No path found
grid = []
for i in range(rows):
row = input(f"Enter row {i + 1} (use 0 for free space and 1 for obstacle, e.g., 0
1 0 0): ").split()
grid.append([int(x) for x in row])
3
start = tuple(map(int, input("Enter start position as 'x y' (e.g., '0 0'):
").split()))
end = tuple(map(int, input("Enter end position as 'x y' (e.g., '4 4'): ").split()))
Output
Enter the number of rows in the grid: 5
Enter the number of columns in the grid: 5
Enter row 1 (use 0 for free space and 1 for obstacle, e.g., 0 1 0 0): 0 1 0 0 0
Enter row 2 (use 0 for free space and 1 for obstacle, e.g., 0 1 0 0): 0 1 0 1 0
Enter row 3 (use 0 for free space and 1 for obstacle, e.g., 0 1 0 0): 0 0 0 1 0
Enter row 4 (use 0 for free space and 1 for obstacle, e.g., 0 1 0 0): 0 1 1 0 0
Enter row 5 (use 0 for free space and 1 for obstacle, e.g., 0 1 0 0): 0 0 0 0 0
Enter start position as 'x y' (e.g., '0 0'): 0 0
Enter end position as 'x y' (e.g., '4 4'): 4 4
Grid you entered:
[0, 1, 0, 0, 0]
[0, 1, 0, 1, 0]
[0, 0, 0, 1, 0]
[0, 1, 1, 0, 0]
[0, 0, 0, 0, 0]
Path found: [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
4
AIPR3
Implement Greedy search algorithm for ‘Kruskal’s Minimal Spanning Tree Algorithm’
class DisjointSet:
def __init__(self, vertices):
self.parent = {v: v for v in vertices}
return mst
edges = []
num_edges = int(input(f"Enter the number of edges: "))
for i in range(num_edges):
u, v, weight = input(f"Enter edge {i+1} (format: u v weight, e.g., A B
3): ").split()
weight = int(weight)
edges.append((u, v, weight))
5
Output
6
AIPR4
Implement a solution for a Constraint Satisfaction Problem using Branch and Bound and Backtracking
for the N-Queens problem or a graph coloring problem.
def is_safe(board, row, col, n):
# Check column
for i in range(row):
if board[i][col] == 1:
return False
return True
# Backtrack
board[row][col] = 0
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
7
board = [[0 for _ in range(n)] for _ in range(n)]
solve(0, set(), set(), set(), board)
Output
. . Q .
Q . . .
. . . Q
. Q . .
. . Q .
Q . . .
. . . Q
. Q . .
8
AIPR5
Develop an elementary chatbot for any suitable customer interaction application.
# Simple Rule-Based Chatbot for Customer Support
def chatbot_response(user_input):
user_input = user_input.lower()
# Run it
run_chatbot()
Output
Customer Support Chatbot � (type 'exit' to quit)
You: hi
Chatbot: Hello! How can I assist you today?
You: how can I track my order?
Chatbot: To check your order status, please enter your order ID at our Order
Tracking page.
You: thanks
Chatbot: You're welcome! Happy to assist you!
You: exit
Chatbot: Thank you for contacting us. Have a great day!
9
AIPR6
Implement any one of the following Expert Systems:
Intonation management
Hospitals and medical facilities
Help desks management
Employee performance evaluation
Stock market trading
Airline scheduling and cargo schedules
def diagnose(symptoms):
symptoms = set(symptom.lower() for symptom in symptoms)
# Main interaction
def medical_expert_system():
print("🏥 Medical Expert System 🏥")
print("Please enter your symptoms separated by commas.")
print("Example: fever, cough, sore throat")
user_input = input("Your Symptoms: ")
symptoms = [sym.strip() for sym in user_input.split(',')]
result = diagnose(symptoms)
print("\nDiagnosis:", result)
# Run it
medical_expert_system()
Output
🏥 Medical Expert System 🏥
Please enter your symptoms separated by commas.
Example: fever, cough, sore throat
Your Symptoms: fever, cough, sore throat
10