Artificial Intelligence Lab File
Artificial Intelligence Lab File
(Lab File)
Name : .
Course : . Sem : .
Subject Name : .
Subject Code : .
Roll no. : .
Date : / / .
Que1. Implement Breadth-First Search (BFS).
Output:
ABDECF
return None
# Example usage
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1)],
'C': [('D', 1), ('E', 5)],
'D': [('F', 2)],
'E': [('F', 2)],
'F': []
}
h = {'A': 7, 'B': 6, 'C': 2, 'D': 1, 'E': 6, 'F': 0}
print(a_star_search(graph, 'A', 'F', h))
Que4. Solve a Constraint Satisfaction Problem (CSP).
Ans: Solve a Sudoku puzzle using backtracking.
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
if board[row - row % 3 + i // 3][col - col % 3 + i % 3] == num:
return False
return True
def solve_sudoku(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0
return False
return True
sudoku = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
if solve_sudoku(sudoku):
for row in sudoku:
print(row)
else:
print("No solution exists")
# Example usage
def fitness(x):
return -(x - 3)**2 + 9 # Maximum at x = 3
def neighbors(x):
return [x - 0.1, x + 0.1]
x0 = random.uniform(0, 6)
result = hill_climbing(fitness, x0, neighbors)
print("Optimum:", result, "Fitness:", fitness(result))
while True:
user_input = input("You: ").lower()
if user_input in responses:
print("Bot:", responses[user_input])
if user_input == "bye":
break
else:
print("Bot: I'm sorry, I don't understand.")
chatbot()
Que7. Solve the 8-Queens Problem.
Ans: Write a Python program to solve the N-Queens problem using backtracking.
def print_board(board):
for row in board:
print(" ".join(row))
print()
res = False
for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 'Q'
res = solve_n_queens(board, col + 1, n) or res
board[i][col] = '.'
return res
n=8
board = [['.' for _ in range(n)] for _ in range(n)]
solve_n_queens(board, 0, n)