0% found this document useful (0 votes)
10 views

AI lab

AI lab manual

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

AI lab

AI lab manual

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

AI

1.Basic Implementation of Breadth First Search and Depth First Search using Python

BFS

from collections import deque

def bfs(graph, start):

# Initialize a queue with the starting node

queue = deque([start])

# Set to keep track of visited nodes

visited = set()

# List to store the BFS traversal order

traversal_order = []

# Mark the starting node as visited

visited.add(start)

while queue:

# Dequeue a node from the front of the queue

node = queue.popleft()

# Add the node to the traversal order

traversal_order.append(node)

# Process each neighbor of the node

for neighbor in graph[node]:


if neighbor not in visited:

# Mark neighbor as visited and enqueue it

visited.add(neighbor)

queue.append(neighbor)

return traversal_order

# Example usage

if __name__ == "__main__":

# Example graph represented as an adjacency list

graph = {

'A': ['B', 'C'],

'B': ['A', 'D', 'E'],

'C': ['A', 'F'],

'D': ['B'],

'E': ['B', 'F'],

'F': ['C', 'E']

start_node = 'A'

print("BFS Traversal Order:", bfs(graph, start_node))

OUTPUT
BFS Traversal Order: ['A', 'B', 'C', 'D', 'E', 'F']

DFS

def dfs(graph, start, visited=None):

if visited is None:
visited = set() # Initialize the visited set if not provided

visited.add(start) # Mark the current node as visited

print(start) # Process the current node (here we are just printing it)

for neighbor in graph[start]:

if neighbor not in visited:

dfs(graph, neighbor, visited) # Recursively visit each neighbor

return visited

# Example usage

# Define a graph as an adjacency list

graph = {

'A': ['B', 'C'],

'B': ['A', 'D', 'E'],

'C': ['A', 'F'],

'D': ['B'],

'E': ['B', 'F'],

'F': ['C', 'E']

# Call DFS starting from node 'A'

dfs(graph, 'A')

OUTPUT
A
B
D
E
F
C
3.Implementation of constraint satisfaction problem using python

def solutions():

# letters = ('s', 'e', 'n', 'd', 'm', 'o', 'r', 'y')

all_solutions = list()

for s in range(9, -1, -1):

for e in range(9, -1, -1):

for n in range(9, -1, -1):

for d in range(9, -1, -1):

for m in range(9, 0, -1):

for o in range(9, -1, -1):

for r in range(9, -1, -1):

for y in range(9, -1, -1):

if len(set([s, e, n, d, m, o, r, y])) == 8:

send = 1000 * s + 100 * e + 10 * n + d

more = 1000 * m + 100 * o + 10 * r + e

money = 10000 * m + 1000 * o + 100 * n + 10 * e + y

if send + more == money:

all_solutions.append((send, more, money))

return all_solutions

print(solutions())

OUTPUT
[(9567, 1085, 10652)]
4.Basic implementation of missionaries-Cannibals problems using python

from collections import deque

# Define the initial and goal states

initial_state = (3, 3, 1) # (Missionaries on left, Cannibals on left, Boat on left)

goal_state = (0, 0, 0) # (Missionaries on left, Cannibals on left, Boat on right)

def is_valid_state(state):

m_left, c_left, _ = state

m_right = 3 - m_left

c_right = 3 - c_left

# Check if the number of missionaries and cannibals is within bounds

if m_left < 0 or c_left < 0 or m_right < 0 or c_right < 0:

return False

# Ensure missionaries are not outnumbered by cannibals on either side

if (m_left > 0 and m_left < c_left) or (m_right > 0 and m_right < c_right):

return False

return True

def get_neighbors(state):

neighbors = []

m_left, c_left, b_left = state


if b_left: # Boat is on the left side

possible_moves = [(-1, 0), (-2, 0), (0, -1), (0, -2), (-1, -1)]

else: # Boat is on the right side

possible_moves = [(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)]

for move in possible_moves:

new_state = (m_left + move[0], c_left + move[1], 1 - b_left)

if is_valid_state(new_state):

neighbors.append(new_state)

return neighbors

def bfs():

queue = deque([(initial_state, [])])

visited = set()

visited.add(initial_state)

while queue:

(current_state, path) = queue.popleft()

if current_state == goal_state:

return path + [current_state]

for neighbor in get_neighbors(current_state):

if neighbor not in visited:

visited.add(neighbor)

queue.append((neighbor, path + [current_state]))

return None
# Run BFS to find the solution

solution = bfs()

if solution:

print("Solution found:")

for state in solution:

print(state)

else:

print("No solution found.")

OUTPUT
(3, 3, 1)
(3, 1, 0)
(3, 2, 1)
(3, 0, 0)
(3, 1, 1)
(1, 1, 0)
(2, 2, 1)
(0, 2, 0)
(0, 3, 1)
(0, 1, 0)
(1, 1, 1)
(0, 0, 0)

5. Basic implementation of Water jug problem

from collections import deque

# Define the jug capacities

jug1_capacity = 4

jug2_capacity = 3

target_volume = 2
# Initial state with both jugs empty

initial_state = (0, 0)

# Function to check if a state is valid

def is_valid_state(state):

jug1, jug2 = state

return 0 <= jug1 <= jug1_capacity and 0 <= jug2 <= jug2_capacity

# Function to perform pour actions

def pour(from_jug, to_jug, state):

jug1, jug2 = state

if from_jug == 1:

if jug1 > 0 and jug2 < jug2_capacity:

amount_poured = min(jug1, jug2_capacity - jug2)

new_jug1 = jug1 - amount_poured

new_jug2 = jug2 + amount_poured

return (new_jug1, new_jug2)

else:

if jug2 > 0 and jug1 < jug1_capacity:

amount_poured = min(jug2, jug1_capacity - jug1)

new_jug1 = jug1 + amount_poured

new_jug2 = jug2 - amount_poured

return (new_jug1, new_jug2)

return None

# Function to solve the water jug problem using depth-first search

def water_jug_dfs():

visited = set()

stack = deque()
stack.append((initial_state, [])) # State and actions taken

while stack:

current_state, actions = stack.pop()

if current_state[0] == target_volume or current_state[1] == target_volume:

return actions

visited.add(current_state)

for action in ["Fill Jug 1", "Fill Jug 2", "Empty Jug 1", "Empty Jug 2", "Pour Jug 1 to Jug 2", "Pour Jug 2
to Jug 1"]:

new_state = None

if action == "Fill Jug 1":

new_state = (jug1_capacity, current_state[1])

elif action == "Fill Jug 2":

new_state = (current_state[0], jug2_capacity)

elif action == "Empty Jug 1":

new_state = (0, current_state[1])

elif action == "Empty Jug 2":

new_state = (current_state[0], 0)

elif action == "Pour Jug 1 to Jug 2":

new_state = pour(1, 2, current_state)

elif action == "Pour Jug 2 to Jug 1":

new_state = pour(2, 1, current_state)

if new_state is not None and new_state not in visited:

new_actions = actions + [action]

stack.append((new_state, new_actions))
return None

# Solve the water jug problem

solution = water_jug_dfs()

if solution:

print("Solution Found:")

for i, action in enumerate(solution, start=1):

print(f"Step {i}: {action}")

else:

print("No solution found.")

OUTPUT
Solution Found:
Step 1: Fill Jug 2
Step 2: Pour Jug 2 to Jug 1
Step 3: Fill Jug 2
Step 4: Pour Jug 2 to Jug 1

7. Basic implementation of Tic Tac Toe game using python

print ("Tic Tac Toe")

def tictactoe_grid(value):

print("\n")

print("\t | |")

print("\t {} | {} | {}". format(value[0], value[1], value[2]))

print('\t_____|_____|_____')

#printing the first three boxes of the 3x3 game board


print("\t | |")

print("\t {} | {} | {}". format(value[3], value[4], value[5]))

print('\t_____|_____|____')

#printing the second three boxes of the 3x3 game board

print("\t | |")

print("\t {} | {} | {}". format(value[6], value[7], value[8]))

print('\t | |')

print("\n")

#printing the last three boxes of the 3x3 game board

tictactoe_grid("xoxxxooox")

OUTPUT
8. Basic implementation of hill climbing using python

import random

# Define the objective function

def objective_function(x):

return -x*2 + 5*x

# Hill Climbing Algorithm

def hill_climbing(max_iterations=10, step_size=2, initial_solution=None):

# Generate a random initial solution if none is provided

if initial_solution is None:

current_solution = random.uniform(-1, 1)

else:

current_solution = initial_solution

# Evaluate the initial solution

current_value = objective_function(current_solution)

for iteration in range(max_iterations):

# Generate a neighboring solution by making a small step

new_solution = current_solution + random.uniform(-step_size, step_size)

# Evaluate the neighboring solution

new_value = objective_function(new_solution)

# If the new solution is better, move to the new solution

if new_value > current_value:


current_solution = new_solution

current_value = new_value

# Print progress

print(f"Iteration {iteration + 1}: x = {current_solution}, f(x) = {current_value}")

return current_solution, current_value

# Run the hill climbing algorithm

best_solution, best_value = hill_climbing (max_iterations=10, step_size=2)

print(f"\n Best solution found: x = {best_solution}, f(x) = {best_value}")

OUTPUT
Iteration 1: x = 1.166075167803011, f(x) = 3.498225503409033
Iteration 2: x = 1.6532551301231317, f(x) = 4.959765390369396
Iteration 3: x = 1.6532551301231317, f(x) = 4.959765390369396
Iteration 4: x = 1.9915037465335874, f(x) = 5.974511239600762
Iteration 5: x = 1.9915037465335874, f(x) = 5.974511239600762
Iteration 6: x = 2.78210045266811, f(x) = 8.34630135800433
Iteration 7: x = 4.487500683318849, f(x) = 13.462502049956548
Iteration 8: x = 6.47754102348248, f(x) = 19.43262307044744
Iteration 9: x = 6.47754102348248, f(x) = 19.43262307044744
Iteration 10: x = 6.703137229175036, f(x) = 20.109411687525107

Best solution found: x = 6.703137229175036, f(x) = 20.109411687525107


9. Basic implementation of Alpha Beta Pruning using Python

import math

# Define a simple game tree (for demonstration)

# Each node contains either a value (for leaf nodes) or None (for internal nodes)

game_tree = {

'A': {'B': {'D': 3, 'E': 5}, 'C': {'F': 6, 'G': 9}}

# Minimax function with alpha-beta pruning

def alpha_beta(node, depth, alpha, beta, maximizing_player, tree):

# Base case: If the node is a leaf node, return its value

if isinstance(tree[node], int):

return tree[node]

if maximizing_player:

max_eval = -math.inf

for child in tree[node]:

eval = alpha_beta(child, depth + 1, alpha, beta, False, tree[node])

max_eval = max(max_eval, eval)

alpha = max(alpha, eval)

if beta <= alpha:

break # Beta cutoff

return max_eval

else:

min_eval = math.inf

for child in tree[node]:


eval = alpha_beta(child, depth + 1, alpha, beta, True, tree[node])

min_eval = min(min_eval, eval)

beta = min(beta, eval)

if beta <= alpha:

break # Alpha cutoff

return min_eval

# Root node is 'A'

best_value = alpha_beta('A', depth=0, alpha=-math.inf, beta=math.inf, maximizing_player=True,


tree=game_tree)

print(f"Best value: {best_value}")

OUTPUT
Best value: 6

You might also like