[go: up one dir, main page]

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

Artificial Intelligence Lab File

Python Program Of AI

Uploaded by

shivamkkushwaha0
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)
22 views10 pages

Artificial Intelligence Lab File

Python Program Of AI

Uploaded by

shivamkkushwaha0
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

Artificial Intelligence

(Lab File)

Name : .

Course : . Sem : .

Subject Name : .

Subject Code : .

Roll no. : .

Date : / / .
Que1. Implement Breadth-First Search (BFS).

Ans: Write a Python program to perform Breadth-First Search on a graph.


from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=" ")
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'E': [],}
bfs(graph, 'A')
Input Graph:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
This graph represents a tree-like structure:
A
/\
B C
/\ \
D E F
Output:
ABCDEF

Ques2. Implement Depth-First Search (DFS)


Ans: Write a Python program to perform Depth-First Search on a graph.
def dfs(graph, node, visited):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
visited = set()
dfs(graph, 'A', visited)

Output:
ABDECF

Que3. Implement A Algorithm*


Ans: Write a Python program for A* search.

from queue import PriorityQueue

def a_star_search(graph, start, goal, h):


open_set = PriorityQueue()
open_set.put((0, start))
came_from = {}
g_score = {node: float('inf') for node in graph}
g_score[start] = 0

while not open_set.empty():


_, current = open_set.get()
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]

for neighbor, cost in graph[current]:


temp_g_score = g_score[current] + cost
if temp_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = temp_g_score
f_score = temp_g_score + h[neighbor]
open_set.put((f_score, neighbor))

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

Que5. Implement Hill Climbing.


Ans: Solve the optimization problem using the Hill Climbing algorithm.
import random

def hill_climbing(f, x0, neighbors):


current = x0
while True:
next_move = max(neighbors(current), key=f, default=None)
if next_move is None or f(next_move) <= f(current):
return current
current = next_move

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

Que6. Implement a Simple Chatbot.


Ans: Write a Python program for a rule-based chatbot.
def chatbot():
responses = {
"hello": "Hi! How can I assist you?",
"how are you": "I'm just a program, but I'm here to help!",
"bye": "Goodbye! Have a great day!"
}

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

def is_safe(board, row, col, n):


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

def solve_n_queens(board, col, n):


if col >= n:
print_board(board)
return True

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)

You might also like