PRACTICAL 1: DFS
def dfsRec(adj, visited,
s, res): visited[s]=True res.append(s)
for i in range(len(adj)):
if adj[s][i]==1 and not visited[i]: dfsRec(adj, visited, i, res)
def DFS(adj): visited=[False]*len(adj)
res=[]
dfsRec(adj, visited, 0, res)
return res
def add_edge(adj, s, t):
adj[s][t]=1
adj[t][s]=1
V=5
adj=[[0]*V for _ in range(V)] edges=[(1,2),(1,0),(2,0),(2,3),(2,4)]
for s, t in edges: add_edge(adj, s, t)
res=DFS(adj)
print(" ".join(map(str, res)))
Practical 2: BFS
def bfs(adj): v=len(adj) res=[]
s=0
from collections import deque
q=deque()
visited=[False]*v visited[s]=True
q.append(s) while q:
curr=q.popleft()
res.append(curr) for
x in adj[curr]:
if not visited[x]: visited[x]=True
q.append(x)
return res
if name ==" main ": adj=[[1,2],[0,2,3],[0,4],[1,4],[2,3]]
ans=bfs(adj) for
i in ans:
print(i, end=" ")
Practical 3: A* Algorithm
import heapq
class PuzzleState:
def init (self,
board, moves=0, prev=None): self.board = board
self.moves = moves self.prev = prev
self.zero_pos = board.index(0) # Position of the blank (0)
def lt (self, other):
# Required for priority queue comparisons
return self.f_cost() < other.f_cost()
def f_cost(self):
return self.moves + self.heuristic()
def heuristic(self):
# Heuristic: Manhattan distance distance = 0
for i, val in enumerate(self.board): if val != 0:
target_x, target_y = divmod(val - 1, 3) current_x, current_y = divmod(i, 3)
distance
+= abs(target_x - current_x) + abs(target_y - current_y)
return distance
def is_goal(self):
return self.board == list(range(1, 9)) + [0]
def generate_neighbors(self): neighbors = []
x, y = divmod(self.zero_pos, 3)
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] #
Up, Down, Left, Right for dx, dy
in directions:
nx, ny = x + dx, y + dy
if
0 <= nx < 3 and 0 <= ny < 3: new_zero_pos = nx * 3 + ny
new_board = self.board[:]
# Swap zero with the
new position
new_board[self.zero_pos], new_board[new_zero_pos] =
new_board[new_zero_pos], new_board[self.zero_pos]
neighbors.append(PuzzleState(new_board, self.moves + 1, self)) return neighbors
def a_star(start_board):
start_state = PuzzleState(start_board) if
start_state.is_goal():
return start_state
open_set = []
heapq.heappush(open_set, start_state)
closed_set = set()
while open_set:
current = heapq.heappop(open_set)
if current.is_goal():
return current
closed_set.add(tuple(current.board))
for neighbor in current.generate_neighbors():
if tuple(neighbor.board) in closed_set:
continue heapq.heappush(open_set, neighbor)
return None
def reconstruct_path(state):
path = []
while state: path.append(state.board)
state = state.prev
return path[::-1]
if name == " main ":
start = [1, 2, 3, 4, 5, 6, 0, 7, 8] # Initial
state solution = a_star(start)
if solution:
print("Solution found in", solution.moves, "moves:")
for step in reconstruct_path(solution):
for i in range(0, 9, 3):
print(step[i:i+3])
print()
else:
print("No solution
found.")
PRACTICAL 4: Selection Sort
def selection_sort(arr):
n=len(arr)
for i in range(n-1):
min_index=i
for j in range(i+1,n):
if arr[j]<arr[min_index]:
min_index=j
arr[i],arr[min_index]=arr[min_index],arr[i]
return arr
arr=[23,45,56,2,12]
print("Original Array :",arr) sorted_arr=selection_sort(arr) print("Sorted Array :",sorted_arr)
PRACTICAL 5: Prim’s Algorithm
import heapq
def prims_algorithm(graph, start): mst = []
visited = set()
min_heap = [(0, start, None)] while min_heap:
weight, current_node, parent
= heapq.heappop(min_heap) if
current_node in visited:
continue
visited.add(current_node) if parent is not None:
mst.append((parent,
current_node, weight))
for neighbor, edge_weight in graph[current_node]:
if neighbor not in visited:
heapq.heappush(min_heap, (edge_weight, neighbor, current_node)) return mst
if name ==
" main ": graph = {
'A': [('B', 1), ('C',
4)],
'B': [('A', 1), ('C', 2), ('D', 6)],
'C': [('A', 4), ('B', 2), ('D', 3)],
'D': [('B', 6), ('C', 3)] }
mst
= prims_algorithm(graph, 'A') print("Minimum Spanning
Tree:") for u, v, w in mst:
print(f"{u} - {v}, weight: {w}")
PRACTICAL 6: CSP
def is_safe(board, row, col, n): for i in range(row):
if board[i] == col or board[i]
- i
== col - row or board[i] + i == col + row:
return False
return True
def solve_n_queens(board, row, n):
if row >= n:
return True
for col
in range(n):
if is_safe(board, row, col, n): board[row] = col # Place queen
if solve_n_queens(board, row + 1, n):
return True
board[row] = -1 return False
def print_solution(board, n): for i in range(n):
row = ['.' for _
in range(n)]
row[board[i]] = 'Q'
print(" ".join(row))
def n_queens(n):
board = [-1] * n
if solve_n_queens(board, 0, n):
print_solution(board, n)
else:
print("No solution exists") n_queens(4)
PRACTICAL 7: Student
Support Chatbot
class StudentSupportChatbot: def init (self):
self.intro_message = "Hello! I am your Student Support
Chatbot. How can I help you today?"
self.commands = {
"courses": self.get_courses, "schedule": self.get_schedule, "location":
self.get_location, "exit": self.exit_chat
}
def get_courses(self):
courses = ["Mathematics", "Physics", "Computer Science", "Biology"]
return "We offer the following courses: " + ",
".join(courses)
def get_schedule(self):
schedule = {
"Mathematics": "Mon-Wed 10:00 AM - 12:00 PM", "Physics":
"Tue-Thu 1:00 PM - 3:00 PM",
"Computer Science": "Mon-Wed 2:00 PM - 4:00 PM", "Biology":
"Tue-Thu 3:00 PM - 5:00 PM"
}
return "\n".join([f"{course}: {time}" for course, time in schedule.items()])
def get_location(self):
return "The university is located
at 123 University Ave, Springfield."
def exit_chat(self):
return "Thank you for chatting
with me! Have a great
day!"
def handle_input(self, user_input): user_input = user_input.lower() if
"course" in user_input:
return self.get_courses() elif "schedule" in user_input:
return self.get_schedule() elif "location" in user_input:
return self.get_location()
elif "exit" in user_input:
return self.exit_chat()
else:
return "Sorry, I didn't understand that. Can you ask something else?"
def start_chat(self): print(self.intro_message) while True:
user_input = input("You: ")
response = self.handle_input(user_input)
print("Chatbot: " + response)
if "exit" in user_input.lower():
break
if name == " main ":
chatbot = StudentSupportChatbot() chatbot.start_chat()
PRACTICAL 8: Medical
Expert System
class MedicalExpertSystem: def init (self):
self.rules = {
'flu': ['fever', 'cough'], 'heart_attack': ['chest pain'],
'meningitis': ['headache', 'stiff neck']
}
def ask_question(self, question):
answer = input(f"{question} (yes/no): ").strip().lower() return answer == 'yes'
def diagnose(self):
symptoms = []
# Collect symptoms from the user print("Welcome to the Medical
Expert System!") if
self.ask_question("Do you have a fever?"):
symptoms.append('fever')
if self.ask_question("Do you have a cough?"):
symptoms.append('cough')
if self.ask_question("Do you have chest
pain?"): symptoms.append('chest pain')
if self.ask_question("Do you have a headache?"):
symptoms.append('headache')
if self.ask_question("Do you have a stiff neck?"): symptoms.append('stiff
neck')
# Diagnose based on the symptoms
diagnosis = self.get_diagnosis(symptoms) if
diagnosis:
print(f"Based on your symptoms, you may have: {diagnosis}")
else:
print("We couldn't identify
a clear diagnosis
based on the symptoms
provided.")
def get_diagnosis(self, symptoms):
for condition, condition_symptoms in self.rules.items():
if all(symptom in symptoms for symptom in condition_symptoms):
return condition
return None # Example
usage
if name ==
" main ": system = MedicalExpertSystem()
system.diagnose()
Comments
Post a Comment