123 - Merged (1) - Merged
123 - Merged (1) - Merged
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
def get_graph_input():
graph = {}
neighbors = input(f"Enter neighbors of node {node} separated by spaces (or leave blank if
none): ").split()
graph[node] = neighbors
return graph
# Main code
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
graph = get_graph_input()
def get_graph_input():
graph = {}
neighbors = list(map(int, input(f"Enter neighbors of node {node} separated by spaces (or leave
blank if none): ").split()))
graph[node] = neighbors
return graph
# Main code
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
bfs(visited, graph, 1) # Change 1 to any valid starting node from the user-provided graph
DFS
graph = {
'5': ['3', '7'],
'3': ['2', '4'],
'7': ['8'],
'2': [],
'4': ['8'],
'8': []
}
visited = set()
for i in range(col):
if board[row][i] == 1:
return False
return True
board[i][col] = 0
return False
def solve_nqueens(N):
solve_nqueens(11)
import heapq
while priority_queue:
current_cost, current_node = heapq.heappop(priority_queue)
if current_node == goal:
# Reached the goal, print the path and cost
path, cost = reconstruct_path(visited, start, goal)
print(f"Shortest path from {start} to {goal}: {path}")
print(f"Shortest distance: {cost}")
return
start_city = 'A'
goal_city = 'F'
import heapq
def get_graph_input():
graph = {}
num_edges = int(input("Enter the number of edges: "))
print("Enter edges in the format 'node1 node2 weight' separated by spaces:")
for _ in range(num_edges):
node1, node2, weight = input().split()
weight = int(weight)
node1 = node1.strip() # Remove leading/trailing spaces
node2 = node2.strip()
if node1 not in graph:
graph[node1] = {}
if node2 not in graph:
graph[node2] = {}
graph[node1][node2] = weight
graph[node2][node1] = weight # Assuming an undirected graph
return graph
while priority_queue:
current_cost, current_node = heapq.heappop(priority_queue)
if current_node == goal:
# Reached the goal, print the path and cost
path, cost = reconstruct_path(visited, start, goal)
print(f"Shortest path from {start} to {goal}: {path}")
print(f"Shortest distance: {cost}")
return
while True:
result, path = depth_limited_search(graph, start, goal, depth_limit)
if result == goal:
return result, path
elif result == 'cutoff':
depth_limit += 1
else:
return None, []
if depth_limit == 0:
return 'cutoff', []
cutoff_occurred = False
for neighbor in graph.get(current, []): # Use .get() to handle nodes without neighbors
if neighbor not in visited:
visited.add(neighbor)
result, subpath = recursive_depth_limited_search(graph, neighbor, goal,
depth_limit - 1, visited, path + [current])
if result == 'cutoff':
cutoff_occurred = True
elif result is not None:
return result, subpath
if cutoff_occurred:
return 'cutoff', []
else:
return None, []
start_node = 'A'
goal_node = 'F'
if result:
print(f"Goal {goal_node} found using Iterative Deepening Search.")
print(f"Path: {' -> '.join(path)}")
else:
print(f"Goal {goal_node} not reachable.")
def get_graph_input():
graph = {}
num_edges = int(input("Enter the number of edges: "))
print("Enter edges in the format 'node1 node2' separated by spaces:")
for _ in range(num_edges):
node1, node2 = input().split()
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1) # Assuming an undirected graph
return graph
while True:
result, path = depth_limited_search(graph, start, goal, depth_limit)
if result == goal:
return result, path
elif result == 'cutoff':
depth_limit += 1
else:
return None, []
if depth_limit == 0:
return 'cutoff', []
cutoff_occurred = False
for neighbor in graph.get(current, []): # Use .get() to handle nodes without neighbors
if neighbor not in visited:
visited.add(neighbor)
result, subpath = recursive_depth_limited_search(graph, neighbor, goal,
depth_limit - 1, visited, path + [current])
if result == 'cutoff':
cutoff_occurred = True
elif result is not None:
return result, subpath
if cutoff_occurred:
return 'cutoff', []
else:
return None, []
if result:
print(f"Goal {goal_node} found using Iterative Deepening Search.")
print(f"Path: {' -> '.join(path)}")
else:
print(f"Goal {goal_node} not reachable.")
def generate_successors(state):
m1, c1, b, m2, c2 = state
successors = []
if b == 0:
successors.extend([(m1 - 1, c1, 1, m2 + 1, c2),
(m1 - 2, c1, 1, m2 + 2, c2),
(m1, c1 - 1, 1, m2, c2 + 1),
(m1 - 1, c1 - 1, 1, m2 + 1, c2 + 1),
(m1, c1 - 2, 1, m2, c2 + 2)])
else:
successors.extend([(m1 + 1, c1, 0, m2 - 1, c2),
(m1 + 2, c1, 0, m2 - 2, c2),
(m1, c1 + 1, 0, m2, c2 - 1),
(m1 + 1, c1 + 1, 0, m2 - 1, c2 - 1),
(m1, c1 + 2, 0, m2, c2 - 2)])
if current_state == goal_state:
return path
return None
def print_solution(path):
for i, state in enumerate(path):
m1, c1, b, m2, c2 = state
print(f"Step {i + 1}: {('M' * m1) + ('C' * c1)} {'B' if b == 0 else ' ' * 3} {('M' *
m2) + ('C' * c2)}")
if __name__ == "__main__":
m1 = int(input("Enter the number of missionaries on the starting side: "))
c1 = int(input("Enter the number of cannibals on the starting side: "))
b=0
m2 = 0
c2 = 0
start_state = (m1, c1, b, m2, c2)
if solution_path:
print("Solution found:")
print_solution(solution_path)
else:
print("No solution found.")
TCS:
from itertools import permutations
def traveling_salesman_bruteforce(distances):
num_cities = len(distances)
cities = list(range(num_cities))
all_paths = permutations(cities)
min_distance = float('inf')
best_path = None
# Example usage:
distances = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
def traveling_salesman_bruteforce(distances):
num_cities = len(distances)
cities = list(range(num_cities))
all_paths = permutations(cities)
min_distance = float('inf')
best_path = None
Bi directional
class AdjacentNode:
def __init__(self, vertex):
self.vertex = vertex
self.next = None
class BidirectionalSearch:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [None] * self.vertices
self.src_queue = list()
self.dest_queue = list()
self.src_visited = [False] * self.vertices
self.dest_visited = [False] * self.vertices
self.src_parent = [None] * self.vertices
self.dest_parent = [None] * self.vertices
def is_intersecting(self):
for i in range(self.vertices):
if self.src_visited[i] and self.dest_visited[i]:
return i
return -1
graph = BidirectionalSearch(vertices)
edges = int(input("Enter the number of edges: "))
print("Enter the edges (src dest) separated by space:")
for _ in range(edges):
edge = list(map(int, input().split()))
graph.add_edge(edge[0], edge[1])
graph.bidirectional_search(src, dest)
class Cell:
def __init__(self):
self.parent_i = 0
self.parent_j = 0
self.f = float('inf')
self.g = float('inf')
self.h = 0
path.append((row, col))
path.reverse()
if not is_valid(src[0], src[1], ROW, COL) or not is_valid(dest[0], dest[1], ROW, COL):
print("Source or destination is invalid")
return
# Check if the source and destination are unblocked
if not is_unblocked(grid, src[0], src[1]) or not is_unblocked(grid, dest[0], dest[1]):
print("Source or the destination is blocked")
return
open_list = []
heapq.heappush(open_list, (0.0, i, j))
found_dest = False
while len(open_list) > 0:
p = heapq.heappop(open_list)
i = p[1]
j = p[2]
closed_list[i][j] = True
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for dir in directions:
new_i = i + dir[0]
new_j = j + dir[1]
if is_valid(new_i, new_j, ROW, COL) and is_unblocked(grid, new_i, new_j) and not
closed_list[new_i][new_j]:
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j
print("The destination cell is found")
trace_path(cell_details, dest)
found_dest = True
return
else:
cell_details[new_i][new_j].f = f_new
cell_details[new_i][new_j].g = g_new
cell_details[new_i][new_j].h = h_new
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j
if not found_dest:
print("Failed to find the destination cell")
def main():
src = list(map(int, input("Enter the source cell coordinates (row col): ").split()))
dest = list(map(int, input("Enter the destination cell coordinates (row col): ").split()))
if __name__ == "__main__":
main()
for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()
best_first_search(source, target, v)
MINMAX
initial_board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
def print_board(board):
for row in board:
print("|".join(row))
print("-----")
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
if maximizing_player:
max_eval = float('-inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
eval = minimax(board, depth + 1, alpha, beta, False)
board[i][j] = ' '
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break # Beta cutoff
return max_eval
else:
min_eval = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
eval = minimax(board, depth + 1, alpha, beta, True)
board[i][j] = ' '
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break # Alpha cutoff
return min_eval
def find_best_move(board):
best_val = float('-inf')
best_move = (-1, -1)
alpha = float('-inf')
beta = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
move_val = minimax(board, 0, alpha, beta, False)
board[i][j] = ' '
return best_move
if check_winner(current_board, 'O'):
print_board(current_board)
print("Congratulations! You won!")
break
if is_full(current_board):
print_board(current_board)
print("It's a tie!")
break
if check_winner(current_board, 'X'):
print_board(current_board)
print("Computer wins! Better luck next time.")
break
if is_full(current_board):
print_board(current_board)
print("It's a tie!")
break
play_game()
ALPHA BETA
import math
if depth == 0 or node.is_terminal():
if maximizing_player:
max_eval = -math.inf
best_move = None
alpha = max_eval
best_move = child_node
break
else:
min_eval = math.inf
best_move = None
beta = min_eval
best_move = child_node
break
# Example usage:
class Node:
self.value = value
def is_terminal(self):
return len(self.children) == 0
def evaluate(self):
return self.value
def generate_children(self):
return self.children
root = Node(0)
class Graph:
# Constructor
def __init__(self): #
Default dictionary to
defaultdict(list)
# Function to add an edge to
self.graph[u].append(v)
queue = []
queue.append(s)
visited[s] = True
while
queue:
# Dequeue a vertex
s = queue.pop(0)
# dequeued vertex s.
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
__name__== '__main__':
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
Implementation In Laptop :
2. Write a Program to Implement Depth First Search
technique.
CODE:
# Python3 program to print DFS traversal
Graph:
# Constructor
def __init__(self):
self.graph = defaultdict(list)
# Function to add an edge to graph
self.graph[u].append(v)
# and print it
visited.add(v) print(v,
end=' ')
neighbour in self.graph[v]: if
self.DFSUtil(neighbour, visited)
# recursive DFSUtil()
visited = set()
== "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
# Function call
g.DFS(2)
3. Write a program to implement the Greedy Best
First Search technique.
CODE:
from typing import List, Tuple
grid = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class Node:
"""
>>> k.calculate_heuristic()
>>> n.calculate_heuristic()
>>> l = [k, n]
>>> n == l[0]
False
>>> l.sort()
>>> n == l[0]
True
"""
self.calculate_heuristic()
"""
"""
dy = abs(self.pos_x - self.goal_x)
dx = abs(self.pos_y - self.goal_y)
return dx + dy
class GreedyBestFirst:
"""
(1, 0)
>>> gbf.retrace_path(gbf.start)
[(0, 0)]
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1),
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
"""
self.open_nodes = [self.start]
self.closed_nodes = []
self.reached = False
"""
"""
while self.open_nodes:
self.open_nodes.sort() current_node =
self.open_nodes.pop(0)
if current_node.pos == self.target.pos:
self.reached = True
return self.retrace_path(current_node)
self.closed_nodes.append(current_node)
successors = self.get_successors(current_node)
if child_node in self.closed_nodes:
continue
self.open_nodes.append(child_node)
else:
better_node = self.open_nodes.pop(self.open_nodes.index(child_node))
self.open_nodes.append(child_node)
else:
self.open_nodes.append(better_node)
if not (self.reached):
return [self.start.pos]
"""
"""
successors = []
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node( pos_x,
pos_y,
self.target.pos_y,
self.target.pos_x,
parent.g_cost + 1,
parent,
return successors
"""
"""
current_node = node
path = [] while
return path
if __name__ == "__main__":
print(elem)
print("------")
path = greedy_bf.search()
grid[elem[0]][elem[1]] = 2
namespace std;
#define ROW 9
#define COL 10
struct cell {
Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int
};
// is in range
return (row >= 0) && (row < ROW) && (col >= 0)
if (grid[row][col] == 1)
return (true);
else
return (false);
return (true);
else
return (false);
return ((double)sqrt(
= dest.second;
stack<Pair> Path;
cellDetails[row][col].parent_j;
row = temp_row;
col = temp_col;
Path.top();
Path.pop();
return;
}
// A Function to find the shortest path between
printf("Source is invalid\n");
return;
printf("Destination is invalid\n");
return;
== false) {
return;
== true) {
return;
}
bool closedList[ROW][COL];
cellDetails[ROW][COL];
int i, j;
cellDetails[i][j].f = FLT_MAX;
cellDetails[i][j].g = FLT_MAX;
cellDetails[i][j].h = FLT_MAX;
cellDetails[i][j].parent_i = -1;
cellDetails[i][j].parent_j = -1;
cellDetails[i][j].parent_i = i;
cellDetails[i][j].parent_j = j;
/*
Create an open list having information as-
f = g + h,
pair.*/
set<pPair> openList;
// Put the starting cell on the open list and set its
// 'f' as 0
while (!openList.empty()) {
pPair p = *openList.begin();
openList.erase(openList.begin());
i = p.second.first;
j = p.second.second;
closedList[i][j] = true;
/*
\|/
\|/
W----Cell----E
/|\
/|\
S.W S S.E
if (isValid(i - 1, j) == true) {
// current successor
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i - 1, j)
== true) {
// OR
openList.insert(make_pair(
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
if (isValid(i + 1, j) == true) {
// current successor
cellDetails[i + 1][j].parent_i = i;
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i + 1, j)
== true) {
= gNew + hNew;
// OR
openList.insert(make_pair(
cellDetails[i + 1][j].parent_i = i;
cellDetails[i + 1][j].parent_j = j;
if (isValid(i, j + 1) == true) {
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].parent_j = j;
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i, j + 1)
== true) {
// OR
openList.insert(make_pair(
cellDetails[i][j + 1].f =
gNew;
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].parent_j = j;
if (isValid(i, j - 1) == true) {
// current successor
cellDetails[i][j - 1].parent_i = i;
tracePath(cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
&& isUnBlocked(grid, i, j - 1)
== true) {
// OR
openList.insert(make_pair(
cellDetails[i][j - 1].parent_i = i;
cellDetails[i][j - 1].parent_j = j;
}
}
//------------
(isValid(i - 1, j + 1) == true) {
// current successor
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i - 1, j + 1)
== true) {
// OR
openList.insert(make_pair(
//------------
if (isValid(i - 1, j - 1) == true) {
// current successor
tracePath(cellDetails, dest);
&& isUnBlocked(grid, i - 1, j - 1)
== true) {
// OR
openList.insert(make_pair(
//------------
if (isValid(i + 1, j + 1) == true) {
// current successor
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i + 1, j + 1)
== true) {
// OR
openList.insert(make_pair(
}
//----------- 8th Successor (South-West)
//------------
if (isValid(i + 1, j - 1) == true) {
// current successor
tracePath(cellDetails, dest);
foundDest = true;
return;
&& isUnBlocked(grid, i + 1, j - 1)
== true) {
// OR
fNew) { openList.insert(make_pair(
return;
}
// Driver program to test above function int
main()
grid[ROW][COL]
= { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } };
return (0);
}
cost = {}
if 'AND' in condition:
AND_nodes = condition['AND']
cost[Path_A] = PathA
if 'OR' in condition:
OR_nodes = condition['OR']
Conditions, weight=1):
Main_nodes = list(Conditions.keys())
key in Main_nodes:
condition = Conditions[key]
least_cost
Path = Start
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_cost)
Next = key[Index].split()
if len(Next) == 1:
Start =Next[0]
else:
Path +='<--('+key[Index]+') '
Start = Next[0]
Start = Next[-1]
return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}
Conditions = {
# weight weight = 1 #
Updated cost
Updated_cost,H))
6. Write a program to implement Simulated Annealing
Algorithm
CODE:
#include <bits/stdc++.h>
class Solution {
public: float
CVRMSE;
vector<int> config;
this->CVRMSE = CVRMSE;
config = configuration;
};
// Function prototype
Solution genRandSol();
T = 1;
M = 5; int N = 5;
temp = {};
Solution genRandSol() {
return currentSol;
return -1.0;
}
// Mapping from [0, M*N] [0,M]x[0,N]
return points;
int main(){
mini = currentSol;
currentSol = newSol;
sourceArray[i][j] = ‘X’;
mini.config.size(); index++){
sourceArray[coord[0]][coord[1]] = ‘-‘;
}
}
7. Write a program to implement Hill Climbing
Algorithm
CODE:
#include <algorithm>
#include <iostream>
#include <vector>
generate_neighbors(int x)
generate_neighbors(
neighbors.begin(), neighbors.end(),
[f](int a, int b) {
// function value
if (f(best_neighbor)
// than x, stop
return x;
// best neighbor
int main()
// Example usage
int x0 = 1;
return 0;
}
Shobhit Tomar
21BIT0093
Artificial Intelligence Lab
Digital Assignment 2
CODE:
import heapq
import itertools
class PuzzleNode:
self.state = state
self.parent = parent
self.move = move
self.cost = parent.cost + 1
else:
self.cost = 0
return hash(str(self.state))
def __repr__(self):
def get_blank_position(self):
if value == 0:
return i, j
def get_children(self):
i, j = self.get_blank_position()
children = []
for new_i, new_j in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
return children
def manhattan_distance(state):
distance = 0
for i in range(3):
for j in range(3):
value = state[i][j]
if value != 0:
goal_i, goal_j = divmod(value - 1, 3)
return distance
def solve_puzzle(initial_state):
initial_node = PuzzleNode(initial_state)
frontier = [initial_node]
visited = set()
while frontier:
current_node = heapq.heappop(frontier)
visited.add(current_node)
if current_node.state == goal_state:
path = []
while current_node.parent:
path.append(current_node.move)
current_node = current_node.parent
path.reverse()
return path
heapq.heappush(frontier, child)
visited.add(child)
initial_state = [
[2, 8, 3],
[1, 6, 4],
[7, 0, 5]
]
goal_state = [
[1, 2, 3],
[8, 0, 4],
[7, 6, 5]
path = solve_puzzle(initial_state)
if path:
print(move)
else:
Code:
def print_board(board):
print("|".join(row))
print("-" * 5)
for i in range(3):
return True
return True
return True
return True
return False
def tic_tac_toe():
current_player = 0
print("Welcome to Tic-Tac-Toe!")
for _ in range(9):
print_board(board)
continue
board[row][col] = players[current_player]
if check_winner(board, players[current_player]):
print_board(board)
return
current_player = 1 - current_player
print_board(board)
print("It's a draw!")
tic_tac_toe()
Output:
Q 3. Write a Program to Implement Water-Jug problem.
Code:
from collections import deque
return jug1 >= 0 and jug2 >= 0 and jug1 <= jug1_capacity and jug2 <= jug2_capacity
# Function to get all possible next states from the current state
next_states = []
# Filling jug1
# Filling jug2
# Emptying jug1
next_states.append((0, jug2))
# Emptying jug2
next_states.append((jug1, 0))
start_state = (0, 0)
visited = set()
while queue:
if current_state == target:
return path
if current_state in visited:
continue
visited.add(current_state)
return None
# Example usage
jug1_capacity = 4
jug2_capacity = 3
target = (2, 0)
if solution:
else:
state_format = "MMMCCC"
initial_state = (3, 0, 3, 0)
goal_state = (0, 0, 0, 3)
actions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, -1), (-1, 1), (1, 1), (-1, -1)]
def successors(state):
successors = []
for a in actions:
successors.append(new_state)
return successors
def is_goal(state):
def print_path(path):
print(state_format % state)
def bfs():
visited = set()
while queue:
if state in visited:
continue
visited.add(state)
if is_goal(state):
print_path(path)
return
bfs()
Output:
Q 5. Write a Program to Implement N-Queens Problem.
Code:
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
if col >= n:
return True
# Consider this column and try placing this queen in all rows one by one
for i in range(n):
board[i][col] = 1
# recur to place rest of the queens
return True
# If placing queen in board[i][col] doesn't lead to a solution, then remove queen from
board[i][col]
board[i][col] = 0
# If queen can not be place in any row in this column col then return false
return False
def solve_n_queens(n):
return None
return board
def print_solution(board):
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j] == 1:
else:
print()
# Test the function
n=4
board = solve_n_queens(n)
if board:
print_solution(board)
Output:
Shobhit tomar
21bit0093
artificial intelligence lab
Digital aSSignment 4
SubmitteD to – tapan kumar DaS Sir
Q1. Find a solution for wumpus world problem.
CODE:
class WumpusWorld:
def __init__(self, size):
self.size = size
self.grid = [[' ' for _ in range(size)] for _ in range(size)]
self.agent_position = (0, 0)
self.has_gold = False
self.wumpus_position = (2, 2) # Example, you can set this
randomly
self.pit_positions = [(1, 1)] # Example, you can set these
randomly
self.grid[self.agent_position[0]][self.agent_position[1]] = 'A'
self.grid[self.wumpus_position[0]][self.wumpus_position[1]] =
'W'
for pit_pos in self.pit_positions:
self.grid[pit_pos[0]][pit_pos[1]] = 'P'
self.grid[0][3] = 'G' # Gold location
def print_world(self):
for row in self.grid:
print(' '.join(row))
def find_gold(self):
visited = set()
self.dfs(self.agent_position[0], self.agent_position[1], visited)
if not self.has_gold:
print("Gold not found!")
# Example usage:
world = WumpusWorld(4)
world.print_world()
world.find_gold()
Output:
Q2. The law says that it is a crime for an American to sell weapons to
hostile nations. The country Nono, an enemy of America, has some
missiles, and all of its missiles were sold to it by Colonel West, who is
American. Using Forward chaining prove that “West is a criminal.”
CODE:
rules = {
"sold_missiles": ["Colonel West", "Nono"],
"american_sold_to_hostile_nations": ["Colonel West"]
}
facts = set()
Output:
Q3. The law says that it is a crime for an American to sell weapons to
hostile nations. The country Nono, an enemy of America, has some
missiles, and all of its missiles were sold to it by Colonel West, who is
American. Using Backward chaining prove that “West is a criminal.”
CODE:
rules = {
"sold_missiles": ["Colonel West", "Nono"],
"american_sold_to_hostile_nations": ["Colonel West"]
}
facts = set()
Output:
Q4. It is estimated that 50% of emails are spam emails. Some
software has been applied to filter these spam emails before they
reach your inbox. A certain brand of software claims that it can
detect 99% of spam emails, and the probability for a false positive (a
non-spam email detected as spam) is 5%. Now if an email is detected
as spam, then what is the probability that it is in fact a non-spam
email?
CODE:
# Prior probability of an email being spam
prior_spam = 0.5
CODE:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
Output:
Name – Shobhit tomar
reg No. – 21bit0093
digital aSSigNmeNt 5
Q1. Write a Program to solve the Monkey Banana Problem.
CODE:
class MonkeyBananaProblem:
self.initial_state = initial_state
possible_actions = []
x, y = state
if y > 0:
possible_actions.append("up")
if y < 4:
possible_actions.append("down")
if x > 0:
possible_actions.append("left")
if x < 4:
possible_actions.append("right")
return possible_actions
x, y = state
if action == "up":
return (x, y - 1)
return (x, y + 1)
return (x - 1, y)
return (x + 1, y)
def goal_test(self, state):
def solve(self):
explored = set()
while frontier:
if self.goal_test(state):
return actions
explored.add(state)
return None
if __name__ == "__main__":
problem = MonkeyBananaProblem(initial_state)
solution = problem.solve()
if solution:
print(solution)
else:
CODE:
class Shakey:
self.room = initial_room
self.boxes = initial_boxes
if direction == 'left':
if self.room[1] > 0:
self.room = (self.room[0], self.room[1] - 1)
else:
if self.room[1] < 4:
else:
if self.room[0] > 0:
else:
print("Cannot move up. Reached the edge of the
room.")
if self.room[0] < 2:
else:
else:
print("Invalid direction.")
def pick_box(self):
if self.room in self.boxes:
self.boxes.remove(self.room)
else:
if len(self.boxes) < 3:
self.boxes.append(self.room)
else:
print("Goal achieved!")
return True
else:
return False
# Initial state
initial_room = (0, 0)
# Goal state
goal_room = (2, 4)
shakey.move('right')
shakey.move('right')
shakey.move('down')
shakey.pick_box()
shakey.move('up')
shakey.move('up')
shakey.move('up')
shakey.put_box()
shakey.move('right')
shakey.move('down')
shakey.move('down')
shakey.pick_box()
shakey.move('up')
shakey.move('up')
shakey.move('right')
shakey.put_box()
shakey.goal_achieved(goal_room, goal_boxes)
OUTPUT:
Q3. Develop the Decision Tree Classification model for a
given dataset and use it to classify a new sample.
CODE:
import pandas as pd
data = pd.read_csv('your_dataset.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# Step 4: Split the data into training and testing sets
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
prediction = clf.predict(new_sample)
print("Prediction:", prediction[0])
OUTPUT:
• XGBoost Classifier,
• Naïve Bayes,
CODE:
# Step 1: Import necessary libraries
import time
data = pd.read_csv('your_dataset.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
classifiers = [
('XGBoost', XGBoostClassifier()),
start_time = time.time()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(f"{name} Confusion
Matrix:\n{confusion_matrix(y_test, y_pred)}\n")
OUTPUT: