0% found this document useful (0 votes)
14 views28 pages

AI Artificial Intelligence

Uploaded by

ligolushguru
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)
14 views28 pages

AI Artificial Intelligence

Uploaded by

ligolushguru
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/ 28

KANPUR INSTITUTE OF TECHNOLOGY

Artificial Intelligence Lab (KCA-351)

Submitted by: Shweta Sachan


Roll No.2301650140095

MCA -2nd Year (3rd Semester)

Session 2024-25

Submitted to:
Mr. Ajeet Singh
(Assistant Professor)

Department of Computer Application


Vision and Mission of the Department
Vision
Department of Computer Application at Kanpur Institute of Technology is
committed to promote professionals with knowledge and understanding, by
providing with latest Technology in Computer Applications so that they
Contribute not only in the progress of software and its applications but even
beset the entire domain of computer technology.

Mission
M1: To impart high quality education in the science of computing.
M2: To prepare educated and skilled computer professionals.
M3: To create excellence by providing comprehensive knowledge of the
latest tools and technologies in the domain of computer science, so that
students strive to become leaders.
M4: To inculcate ethical values in students so that they understand their
responsibility towards the nation with focus on upliftment of all sections of
society.
M5: To facilitate establishment of research centers and encourage students
to solve complex technological problems.
Program Educational Objectives
PEO1: Make valuable contributions to design, development and production
in the practice of computer science and engineering in related engineering
areas or application areas, and at the interface of computers and physical
systems.

PEO2: Promotes design, research and implementation of products through


strong communication skills, leadership and entrepreneurial skills.

PEO3: Engage in professional development or post-graduate education to


pursue flexible career paths amid future technological changes.

PEO4: Apply basic principles and practices of computing and science to


successfully complete software related projects to meet customer business
objectives and/or productively engage in research.

PEO5: To develop analytical, mathematical and scientific knowledge that is


used to analyze, formulate and solve any engineering problems.

Program specific outcomes (PSO’s):


PSO1: Ability to understand the mathematical methodology to cracks
problems using suitable data structure and mathematical approach.

PSO2: Ability to design and develop software for web based and mobiles
androids under real world environment.

PSO3: Ability to design the algorithm for machine learning, data


compression and IOT based application and also the successful career and
entrepreneurship.
INDEX

S. Name of Experiment Page Date Signature


No No.
1. Write a program to implement Breath First Search 03/09/2024
using python.
2. Write a program to implement Depth First Search 17/09/2024
using python.
3. Write a program to implement TIC-TAC-TOE game 24/09/2024
using python.
4. Write a program to implement 8 Puzzle problem using 15/10/2024
python.
5. Write a program to implement Water-jug problem 22/10/2024
using python.
6. Write a program to implement Travelling Salesman 05/11/2024
problem using python.
7. Write a program to implement Tower of Hanoi using 12/11/2024
python.
8. Write a program to implement Monkey Banana 04/12/2024
problem using python.
9. Write a program to implement Alpha-Beta pruning 10/12/2024
using python.
10. Write a program to implement 8-Queens Problem 16/12/2024
using python.
Experiment No: 01
Write a program to implement Breath First Search using python.

from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
visited.add(start)

while queue:
vertex = queue.popleft()
print(vertex, end=" ")

for neighbor in graph[vertex]:


if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

# Example usage:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}

bfs(graph, 'A')
Experiment No: 02
Write a program to implement Depth First Search using python.

# Depth First Search in Python

# Using a stack to implement DFS


def dfs(graph, start):
visited = set() # Set to keep track of visited nodes
stack = [start] # Stack to keep track of nodes to visit

while stack:
vertex = stack.pop() # Get the last node from the stack
if vertex not in visited:
print(vertex, end=" ") # Print the visited node
visited.add(vertex) # Mark the node as visited
stack.extend(graph[vertex] - visited) # Add unvisited neighbors to the stack

# 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'}
}

# Starting the DFS traversal from node 'A'


dfs(graph, 'A')
Experiment No: 03
Write a program to implement TIC-TAC-TOE game using python.

# Tic-Tac-Toe Program using


# random number in Python

# importing all necessary libraries


import numpy as np
import random
from time import sleep

# Creates an empty board

def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

# Check for empty places on board

def possibilities(board):
l = []

for i in range(len(board)):
for j in range(len(board)):

if board[i][j] == 0:
l.append((i, j))
return(l)

# Select a random place for the player

def random_place(board, player):


selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

# Checks whether the player has three


# of their marks in a horizontal row

def row_win(board, player):


for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three


# of their marks in a vertical row

def col_win(board, player):


for x in range(len(board)):
win = True

for y in range(len(board)):
if board[y][x] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three


# of their marks in a diagonal row

def diag_win(board, player):


win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win

# Evaluates whether there is


# a winner or a tie

def evaluate(board):
winner = 0

for player in [1, 2]:


if (row_win(board, player) or
col_win(board, player) or
diag_win(board, player)):

winner = player

if np.all(board != 0) and winner == 0:


winner = -1
return winner

# Main function to start the game

def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)

while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)

# Driver Code
print("Winner is: " + str(play_game()))
Experiment No: 04
Write a program to implement 8 Puzzle problem using python.

# Python3 program to print the path from root


# node to destination node for N*N-1 puzzle
# algorithm using Branch and Bound
# The solution assumes that instance of
# puzzle is solvable

# Importing copy for deepcopy function


import copy

# Importing the heap functions from python


# library for Priority Queue
from heapq import heappush, heappop

# This variable can be changed to change


# the program from 8 puzzle(n=3) to 15
# puzzle(n=4) to 24 puzzle(n=5)...
n=3

# bottom, left, top, right


row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]

# A class for Priority Queue


class priorityQueue:

# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []

# Inserts a new key 'k'


def push(self, k):
heappush(self.heap, k)

# Method to remove minimum element


# from Priority Queue
def pop(self):
return heappop(self.heap)

# Method to know if the Queue is empty


def empty(self):
if not self.heap:
return True
else:
return False

# Node structure
class node:

def __init__(self, parent, mat, empty_tile_pos,


cost, level):

# Stores the parent node of the


# current node helps in tracing
# path when the answer is found
self.parent = parent

# Stores the matrix


self.mat = mat

# Stores the position at which the


# empty space tile exists in the matrix
self.empty_tile_pos = empty_tile_pos

# Stores the number of misplaced tiles


self.cost = cost

# Stores the number of moves so far


self.level = level

# This method is defined so that the


# priority queue is formed based on
# the cost variable of the objects
def __lt__(self, nxt):
return self.cost < nxt.cost
# Function to calculate the number of
# misplaced tiles ie. number of non-blank
# tiles not in their goal position
def calculateCost(mat, final) -> int:

count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1

return count

def newNode(mat, empty_tile_pos, new_empty_tile_pos,


level, parent, final) -> node:

# Copy data from parent matrix to current matrix


new_mat = copy.deepcopy(mat)

# Move tile by 1 position


x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]

# Set number of misplaced tiles


cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,


cost, level)
return new_node

# Function to print the N x N matrix


def printMatrix(mat):

for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")

print()

# Function to check if (x, y) is a valid


# matrix coordinate
def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

# Print path from root node to destination node


def printPath(root):

if root == None:
return

printPath(root.parent)
printMatrix(root.mat)
print()

# Function to solve N*N - 1 puzzle algorithm


# using Branch and Bound. empty_tile_pos is
# the blank tile position in the initial state.
def solve(initial, empty_tile_pos, final):

# Create a priority queue to store live


# nodes of search tree
pq = priorityQueue()

# Create the root node


cost = calculateCost(initial, final)
root = node(None, initial,
empty_tile_pos, cost, 0)

# Add root to list of live nodes


pq.push(root)

# Finds a live node with least cost,


# add its children to list of live
# nodes and finally deletes it from
# the list.
while not pq.empty():

# Find a live node with least estimated


# cost and delete it from the list of
# live nodes
minimum = pq.pop()

# If minimum is the answer node


if minimum.cost == 0:

# Print the path from root to


# destination;
printPath(minimum)
return

# Generate all possible children


for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]

if isSafe(new_tile_pos[0], new_tile_pos[1]):

# Create a child node


child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)

# Add child to list of live nodes


pq.push(child)

# Driver Code

# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

# Solvable Final configuration


# Value 0 is used for empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]

# Blank tile coordinates in


# initial configuration
empty_tile_pos = [ 1, 2 ]

# Function call to solve the puzzle


solve(initial, empty_tile_pos, final)

# This code is contributed by Kevin Joshi


Experiment No: 05
Write a program to implement Water-jug problem using python.
from collections import deque

# Function to find the minimum operations to obtain


# d liters in one jug
def min_steps(m, n, d):
if d > max(m, n):
return -1

# Queue for BFS: (jug1, jug2, steps)


q = deque([(0, 0, 0)])

# For tracking the visited states


visited = [[False] * (n + 1) for _ in range(m + 1)]
visited[0][0] = True

while q:
jug1, jug2, steps = q.popleft()

if jug1 == d or jug2 == d:
return steps

# 1: Fill jug1
if not visited[m][jug2]:
visited[m][jug2] = True
q.append((m, jug2, steps + 1))

# 2: Fill jug2
if not visited[jug1][n]:
visited[jug1][n] = True
q.append((jug1, n, steps + 1))

# 3: Empty jug1
if not visited[0][jug2]:
visited[0][jug2] = True
q.append((0, jug2, steps + 1))

# 4: Empty jug2
if not visited[jug1][0]:
visited[jug1][0] = True
q.append((jug1, 0, steps + 1))

# 5: Pour jug1 into jug2


pour1to2 = min(jug1, n - jug2)
if not visited[jug1 - pour1to2][jug2 + pour1to2]:
visited[jug1 - pour1to2][jug2 + pour1to2] = True
q.append((jug1 - pour1to2, jug2 + pour1to2, steps + 1))

# 6: Pour jug2 into jug1


pour2to1 = min(jug2, m - jug1)
if not visited[jug1 + pour2to1][jug2 - pour2to1]:
visited[jug1 + pour2to1][jug2 - pour2to1] = True
q.append((jug1 + pour2to1, jug2 - pour2to1, steps + 1))

return -1

if __name__ == "__main__":

# jug1 = 4 litre, jug2 = 3 litre


m, n, d = 4, 3, 2
print(min_steps(m, n, d))

Output:
Steps:
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2
Experiment No: 06
Write a program to implement Travelling Salesman problem using python.

n = 4 # there are four nodes in example graph (graph is 1-based)

# dist[i][j] represents shortest distance to go from i to j


# this matrix can be calculated for any given graph using
# all-pair shortest path algorithms
dist = [[0, 0, 0, 0, 0], [0, 0, 10, 15, 20], [
0, 10, 0, 25, 25], [0, 15, 25, 0, 30], [0, 20, 25, 30, 0]]

# memoization for top down recursion


memo = [[-1]*(1 << (n+1)) for _ in range(n+1)]

def fun(i, mask):


# base case
# if only ith bit and 1st bit is set in our mask,
# it implies we have visited all other nodes already
if mask == ((1 << i) | 3):
return dist[1][i]

# memoization
if memo[i][mask] != -1:
return memo[i][mask]

res = 10**9 # result of this sub-problem

# we have to travel all nodes j in mask and end the path at ith node
# so for every node j in mask, recursively calculate cost of
# travelling all nodes in mask
# except i and then travel back from node j to node i taking
# the shortest path take the minimum of all possible j nodes
for j in range(1, n+1):
if (mask & (1 << j)) != 0 and j != i and j != 1:
res = min(res, fun(j, mask & (~(1 << i))) + dist[j][i])
memo[i][mask] = res # storing the minimum value
return res
# Driver program to test above logic
ans = 10**9
for i in range(1, n+1):
# try to go from node 1 visiting all nodes in between to i
# then return from i taking the shortest route to 1
ans = min(ans, fun(i, (1 << (n+1))-1) + dist[i][1])

print("The cost of most efficient tour = " + str(ans))


Experiment No: 07
Write a program to implement Tower of Hanoi using python.

# Recursive Python function to solve the tower of hanoi

def TowerOfHanoi(n , source, destination, auxiliary):


if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)

# Driver code
n=4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
Experiment No: 08
Write a program to implement Monkey Banana problem using python.

class State:
def __init__(self, monkey, box, banana):
self.monkey = monkey # Position of the monkey
self.box = box # Position of the box
self.banana = banana # Position of the banana

def __str__(self):
return f"Monkey: {self.monkey}, Box: {self.box}, Banana: {self.banana}"

def push_box(state):
if not state.box and not state.monkey:
return State(state.monkey, True, state.banana)
return state

def climb_box(state):
if state.box and not state.monkey:
return State(True, state.box, state.banana)
return state

def grab_banana(state):
if state.monkey and state.banana:
print("Banana grabbed!")
return State(state.monkey, state.box, True)
return state

def monkey_banana_problem():
initial_state = State(False, False, False)
print("Initial State:", initial_state)
state = push_box(initial_state)
print("After pushing the box:", state)
state = climb_box(state)
print("After climbing the box:", state)
state = grab_banana(state)

if __name__ == "__main__":
monkey_banana_problem()
Experiment No: 09
Write a program to implement Alpha-Beta pruning using python.
# Python3 program to demonstrate
# working of Alpha-Beta Pruning

# Initial values of Alpha and Beta


MAX, MIN = 1000, -1000

# Returns optimal value for current player


#(Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
values, alpha, beta):

# Terminating condition. i.e


# leaf node is reached
if depth == 3:
return values[nodeIndex]

if maximizingPlayer:

best = MIN

# Recur for left and right children


for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)

# Alpha Beta Pruning


if beta <= alpha:
break

return best

else:
best = MAX
# Recur for left and
# right children
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)

# Alpha Beta Pruning


if beta <= alpha:
break

return best

# Driver Code
if __name__ == "__main__":

values = [3, 5, 6, 9, 1, 2, 0, -1]


print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))
Experiment No: 10
Write a program to implement 8-Queens Problem using python.

# Python program to solve N Queen


# Problem using backtracking

global N
N=4

def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()

# A utility function to check if a queen can


# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):

# Check this row on left side


for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on left side


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

# Check lower diagonal on left side


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

def solveNQUtil(board, col):


# base case: If all queens are placed
# then 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):

if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1

# recur to place rest of the queens


if solveNQUtil(board, col + 1) == True:
return True

# If placing queen in board[i][col


# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0

# if the queen can not be placed in any row in


# this column col then return false
return False

# This function solves the N Queen problem using


# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]

if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False

printSolution(board)
return True

# driver program to test above function


solveNQ()

You might also like