0% found this document useful (0 votes)
9 views10 pages

AI Practicals

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

AI Practicals

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

AIPR1

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

# Depth First Search (DFS) - Recursive


def dfs(graph, vertex, visited=None):
if visited is None:
visited = set()

visited.add(vertex)
print(vertex, end=' ')

for neighbor in graph[vertex]:


if neighbor not in visited:
dfs(graph, neighbor, visited)

# Breadth First Search (BFS) - Iterative


def bfs(graph, start):
visited = set()
queue = deque([start])

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)

# Main function to get user input and run DFS/BFS


def main():
print("Enter the graph details:")
graph = get_graph_from_user()

start_vertex = input("Enter the starting vertex for DFS and BFS: ")

print("\nDepth First Search (DFS):")


dfs(graph, start_vertex)

print("\n\nBreadth First Search (BFS):")


bfs(graph, start_vertex)

# Run the main function


main()

1
Output

Enter the graph details:


Enter the number of vertices: 5
Enter vertex name (e.g., A, B, C, etc.): A
Enter neighbors of A (comma-separated): B,C
Enter vertex name (e.g., A, B, C, etc.): B
Enter neighbors of B (comma-separated): C,E
Enter vertex name (e.g., A, B, C, etc.): E
Enter neighbors of E (comma-separated): A,B
Enter vertex name (e.g., A, B, C, etc.): C
Enter neighbors of C (comma-separated): D,A
Enter vertex name (e.g., A, B, C, etc.): D
Enter neighbors of D (comma-separated): A,B,E
Enter the starting vertex for DFS and BFS: A

Depth First Search (DFS):


A B C D E

Breadth First Search (BFS):


A B C E D

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

def __lt__(self, other):


return self.f < other.f

def heuristic(a, b):


# Manhattan distance (good for grid movement)
return abs(a[0] - b[0]) + abs(a[1] - b[1])

def astar(grid, start, end):


open_list = []
closed_set = set()

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

for next_pos in neighbors:


(nx, ny) = next_pos
if nx < 0 or ny < 0 or nx >= len(grid) or ny >= len(grid[0]):
continue # Out of bounds
if grid[nx][ny] == 1:
continue # Wall or obstacle
if next_pos in closed_set:
continue # Already evaluated

neighbor = Node(next_pos, current_node)


neighbor.g = current_node.g + 1
neighbor.h = heuristic(neighbor.position, end_node.position)
neighbor.f = neighbor.g + neighbor.h

heapq.heappush(open_list, neighbor)
return None # No path found

# Get grid size and values from user input


def get_user_input():
rows = int(input("Enter the number of rows in the grid: "))
cols = int(input("Enter the number of columns in the grid: "))

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()))

return grid, start, end

# Main function to run the algorithm


def main():
grid, start, end = get_user_input()

print("Grid you entered:")


for row in grid:
print(row)

path = astar(grid, start, end)


if path:
print("\nPath found:", path)
else:
print("\nNo path found")

# Run the main function


main()

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}

def find(self, v):


if self.parent[v] != v:
self.parent[v] = self.find(self.parent[v])
return self.parent[v]

def union(self, u, v):


root_u = self.find(u)
root_v = self.find(v)
if root_u != root_v:
self.parent[root_v] = root_u

def kruskal(vertices, edges):


# Sort edges based on weight
edges.sort(key=lambda x: x[2])
ds = DisjointSet(vertices)
mst = []

for u, v, weight in edges:


if ds.find(u) != ds.find(v):
mst.append((u, v, weight))
ds.union(u, v)

return mst

# Get input from the user


def get_user_input():
vertices = input("Enter vertices (comma separated, e.g., A, B, C, D):
").split(',')
vertices = [v.strip() for v in vertices]

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))

return vertices, edges

# Main function to run Kruskal's algorithm


def main():
vertices, edges = get_user_input()

mst = kruskal(vertices, edges)


print("\nEdges in the Minimum Spanning Tree:")
for u, v, weight in mst:
print(f"{u} - {v}: {weight}")

# Run the main function


main()

5
Output

Enter vertices (comma separated, e.g., A, B, C, D): A,B,C,D,E


Enter the number of edges: 7
Enter edge 1 (format: u v weight, e.g., A B 3): A B 1
Enter edge 2 (format: u v weight, e.g., A B 3): A C 3
Enter edge 3 (format: u v weight, e.g., A B 3): C B 2
Enter edge 4 (format: u v weight, e.g., A B 3): B D 1
Enter edge 5 (format: u v weight, e.g., A B 3): D E 5
Enter edge 6 (format: u v weight, e.g., A B 3): C D 2
Enter edge 7 (format: u v weight, e.g., A B 3): C E 4

Edges in the Minimum Spanning Tree:


A - B: 1
B - D: 1
C - B: 2
C - E: 4

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

# Check left diagonal


for i, j in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)):
if board[i][j] == 1:
return False

# Check right diagonal


for i, j in zip(range(row - 1, -1, -1), range(col + 1, n)):
if board[i][j] == 1:
return False

return True

# N-Queens using Backtracking


def solve_n_queens_backtracking(board, row, n):
if row == n:
print_board(board, n)
return

for col in range(n):


if is_safe(board, row, col, n):
board[row][col] = 1
solve_n_queens_backtracking(board, row + 1, n)
board[row][col] = 0 # backtrack

def print_board(board, n):


for i in range(n):
for j in range(n):
print('Q' if board[i][j] else '.', end=' ')
print()
print()

# N-Queens using Branch and Bound (Optimized Backtracking)


def solve_n_queens_branch_and_bound(n):
def solve(row, cols, diag1, diag2, board):
if row == n:
print_board(board, n)
return

for col in range(n):


if col not in cols and (row - col) not in diag1 and (row + col) not
in diag2:
board[row][col] = 1
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)

solve(row + 1, cols, diag1, diag2, board)

# 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)

# Get user input


def get_user_input():
n = int(input("Enter the size of the board (N for N-Queens problem): "))
return n

# Main function to run both algorithms


def main():
n = get_user_input()

print(f"Solutions using Backtracking for {n}-Queens:")


board = [[0 for _ in range(n)] for _ in range(n)]
solve_n_queens_backtracking(board, 0, n)

print(f"Solutions using Branch and Bound for {n}-Queens:")


solve_n_queens_branch_and_bound(n)

# Run the main function


main()

Output

Enter the size of the board (N for N-Queens problem): 4


Solutions using Backtracking for 4-Queens:
. Q . .
. . . Q
Q . . .
. . Q .

. . Q .
Q . . .
. . . Q
. Q . .

Solutions using Branch and Bound for 4-Queens:


. 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()

if "hello" in user_input or "hi" in user_input:


return "Hello! How can I assist you today?"
elif "price" in user_input:
return "Our prices vary depending on the product. Please visit our
website for detailed pricing."
elif "order status" in user_input or "track order" in user_input:
return "To check your order status, please enter your order ID at our
Order Tracking page."
elif "refund" in user_input:
return "Refunds are processed within 5-7 business days after receiving
the returned product."
elif "thank you" in user_input or "thanks" in user_input:
return "You're welcome! Happy to assist you!"
else:
return "I'm sorry, I didn't understand that. Can you please rephrase your
question?"

# Main chatbot loop


def run_chatbot():
print("Customer Support Chatbot � (type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Thank you for contacting us. Have a great day!")
break
response = chatbot_response(user_input)
print("Chatbot:", response)

# 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

# Simple Medical Expert System

def diagnose(symptoms):
symptoms = set(symptom.lower() for symptom in symptoms)

if {'fever', 'cough', 'sore throat'}.issubset(symptoms):


return "You might have the Flu."
elif {'fever', 'rash', 'red eyes'}.issubset(symptoms):
return "You might have Measles."
elif {'headache', 'nausea', 'sensitivity to light'}.issubset(symptoms):
return "You might have Migraine."
elif {'chest pain', 'shortness of breath', 'nausea'}.issubset(symptoms):
return "You might have a Heart Problem. Please seek immediate medical
help."
elif {'stomach pain', 'diarrhea', 'vomiting'}.issubset(symptoms):
return "You might have a Food Infection."
else:
return "Diagnosis unclear. Please consult a doctor."

# 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

Diagnosis: You might have the Flu.

10

You might also like