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

R22-AI Lab Manual

The document is a lab manual for an Artificial Intelligence course, detailing Python programming exercises for various algorithms and problems. It includes implementations for Breadth First Search, Depth First Search, Tic-Tac-Toe, 8-Puzzle, Water-Jug problem, and others. Each section provides code examples and expected outputs for the respective algorithms.

Uploaded by

bharathpatel612
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)
4 views

R22-AI Lab Manual

The document is a lab manual for an Artificial Intelligence course, detailing Python programming exercises for various algorithms and problems. It includes implementations for Breadth First Search, Depth First Search, Tic-Tac-Toe, 8-Puzzle, Water-Jug problem, and others. Each section provides code examples and expected outputs for the respective algorithms.

Uploaded by

bharathpatel612
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/ 24

ARTIFICIAL INTELLIGENCE

LAB MANUAL

III - B. Tech – II Semester

Department of Computer Science & Engineering


SREE CHAITANYA INSTITUTE OF TECHNOLOGICAL SCIENCES
LMD COLONY, KARIMNAGAR-505527
(Approved by AICTE, Affiliated to JNTUH, Hyderabad)
INDEX
EXPERIMENT NAME PAGE NO

Write the Program to Implement the following using Python.


1. Breadth First Search 3
2. Depth First Search 4
3. Tic-Tac-Toe game 5
4. 8-Puzzle problem 9
5. Water-Jug problem 16
6. Travelling Salesman Problem 18
7. Tower of Hanoi 19
8. Monkey Banana Problem 20
9. Alpha-Beta Pruning 21
10. 8-Queens Problem 23

2
1). Write a program to implement Breadth first search using Python

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Output:
Following is the Breadth-First Search
5 3 7 2 4 8

3
2). Write a program to implement Depth first search using Python

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Output:
Following is the Depth-First Search
5 3 2 4 8 7

4
3). Write a program to implement Tic-Toc-Toe using 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

5
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

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

7
Output:
[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1 move
[[0 0 0]
[0 0 0]
[1 0 0]]
Board after 2 move
[[0 0 0]
[0 2 0]
[1 0 0]]
Board after 3 move
[[0 1 0]
[0 2 0]
[1 0 0]]
Board after 4 move
[[0 1 0]
[2 2 0]
[1 0 0]]
Board after 5 move
[[1 1 0]
[2 2 0]
[1 0 0]]
Board after 6 move
[[1 1 0]
[2 2 0]
[1 2 0]]
Board after 7 move
[[1 1 0]
[2 2 0]
[1 2 1]]
Board after 8 move
[[1 1 0]
[2 2 2]
[1 2 1]]
Winner is: 2

8
4). Write a program to implement 8-Puzzle problem using Python

# Python code to display the way from the root


# node to the final destination node for N*N-1 puzzle
# algorithm by the help of Branch and Bound technique
# The answer assumes that the instance of the
# puzzle can be solved

# Importing the 'copy' for deepcopy method


import copy

# Importing the heap methods from the python


# library for the Priority Queue
from heapq import heappush, heappop

# This particular var can be changed to transform


# the program from 8 puzzle(n=3) into 15
# puzzle(n=4) and so on ...
n=3

# bottom, left, top, right


rows = [ 1, 0, -1, 0 ]
cols = [ 0, -1, 0, 1 ]

# creating a class for the Priority Queue


class priorityQueue:

# Constructor for initializing a


# Priority Queue
def __init__(self):
self.heap = []

# Inserting a new key 'key'

9
def push(self, key):
heappush(self.heap, key)

# funct to remove the element that is minimum,


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

# funct to check if the Queue is empty or not


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

# structure of the node


class nodes:

def __init__(self, parent, mats, empty_tile_posi,


costs, levels):

# This will store the parent node to the


# current node And helps in tracing the
# path when the solution is visible
self.parent = parent

# Useful for Storing the matrix


self.mats = mats

# useful for Storing the position where the


# empty space tile is already existing in the matrix
self.empty_tile_posi = empty_tile_posi

# Store no. of misplaced tiles

10
self.costs = costs

# Store no. of moves so far


self.levels = levels

# This func is used in order to form the


# priority queue based on
# the costs var of objects
def __lt__(self, nxt):
return self.costs < nxt.costs

# method to calc. the no. of


# misplaced tiles, that is the no. of non-blank
# tiles not in their final posi
def calculateCosts(mats, final) -> int:

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

return count

def newNodes(mats, empty_tile_posi, new_empty_tile_posi,


levels, parent, final) -> nodes:

# Copying data from the parent matrixes to the present matrixes


new_mats = copy.deepcopy(mats)

# Moving the tile by 1 position


x1 = empty_tile_posi[0]
y1 = empty_tile_posi[1]

11
x2 = new_empty_tile_posi[0]
y2 = new_empty_tile_posi[1]
new_mats[x1][y1], new_mats[x2][y2] = new_mats[x2][y2], new_mats[x1][y1]

# Setting the no. of misplaced tiles


costs = calculateCosts(new_mats, final)

new_nodes = nodes(parent, new_mats, new_empty_tile_posi,


costs, levels)
return new_nodes

# func to print the N by N matrix


def printMatsrix(mats):

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

print()

# func to know if (x, y) is a valid or invalid


# matrix coordinates
def isSafe(x, y):

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

# Printing the path from the root node to the final node
def printPath(root):

if root == None:
return

printPath(root.parent)
printMatsrix(root.mats)

12
print()

# method for solving N*N - 1 puzzle algo


# by utilizing the Branch and Bound technique. empty_tile_posi is
# the blank tile position initially.
def solve(initial, empty_tile_posi, final):

# Creating a priority queue for storing the live


# nodes of the search tree
pq = priorityQueue()

# Creating the root node


costs = calculateCosts(initial, final)
root = nodes(None, initial,
empty_tile_posi, costs, 0)

# Adding root to the list of live nodes


pq.push(root)

# Discovering a live node with min. costs,


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

# Finding a live node with min. estimatsed


# costs and deleting it form the list of the
# live nodes
minimum = pq.pop()

# If the min. is ans node


if minimum.costs == 0:

# Printing the path from the root to

13
# destination;
printPath(minimum)
return

# Generating all feasible children


for i in range(n):
new_tile_posi = [
minimum.empty_tile_posi[0] + rows[i],
minimum.empty_tile_posi[1] + cols[i], ]

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

# Creating a child node


child = newNodes(minimum.mats,
minimum.empty_tile_posi,
new_tile_posi,
minimum.levels + 1,
minimum, final,)

# Adding the child to the list of live nodes


pq.push(child)

# Main Code

# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

# Final configuration that can be solved


# Value 0 is taken as an empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],

14
[ 0, 7, 4 ] ]

# Blank tile coordinates in the


# initial configuration
empty_tile_posi = [ 1, 2 ]

# Method call for solving the puzzle


solve(initial, empty_tile_posi, final)

Output:

1 2 3
5 6 0
7 8 4

1 2 3
5 0 6
7 8 4

1 2 3
5 8 6
7 0 4

1 2 3
5 8 6
0 7 4

15
5). Write a program to implement Water-Jug problem using Python

from collections import deque


def Solution(a, b, target):
m = {}
isSolvable = False
path = []

q = deque()

#Initializing with jugs being empty


q.append((0, 0))

while (len(q) > 0):

# Current state
u = q.popleft()
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
path.append([u[0], u[1]])

m[(u[0], u[1])] = 1

if (u[0] == target or u[1] == target):


isSolvable = True

if (u[0] == target):
if (u[1] != 0):
path.append([u[0], 0])
else:
if (u[0] != 0):

path.append([0, u[1]])

sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break

q.append([u[0], b]) # Fill Jug2


q.append([a, u[1]]) # Fill Jug1

16
for ap in range(max(a, b) + 1):
c = u[0] + ap
d = u[1] - ap

if (c == a or (d == 0 and d >= 0)):


q.append([c, d])

c = u[0] - ap
d = u[1] + ap

if ((c == 0 and c >= 0) or d == b):


q.append([c, d])

q.append([a, 0])

q.append([0, b])

if (not isSolvable):
print("Solution not possible")

if __name__ == '__main__':

Jug1, Jug2, target = 4, 3, 2


print("Path from initial state "
"to solution state ::")

Solution(Jug1, Jug2, target)

Output:

Path of states by jugs followed is :


0,0
0,3
3,0
3,3
4,2
0,2

17
6). Write a program to implement Travelling Salesman problem using Python

from sys import maxsize


from itertools, import permutations
V=4
def tsp(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_cost = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_cost = 0
k=s
for j in i:
current_cost += graph[k][j]
k=j
current_cost += graph[k][s]
min_cost = min(min_cost, current_cost)
return min_cost
graph = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(tsp(graph, s))

Output:

80

18
7). Write a program to implement Tower of Hanoi using Python

# Recursive Python function to solve tower of hanoi

def TowerOfHanoi(n, from_rod, to_rod, aux_rod):


if n == 0:
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

# Driver code
N=3

# A, C, B are the name of rods


TowerOfHanoi(N, 'A', 'C', 'B')

Output:

Move disk 1 from rod A to rod C


Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

19
8). Write a program to implement Monkey Banana Problem using Python

import random

class Monkey:
def __init__(self, bananas):
self.bananas = bananas

def __repr__(self):
return "Monkey with %d bananas." % self.bananas

monkeys = [Monkey(random.randint(0, 50)) for i in range(5)]

print "Random monkeys:"


print monkeys

print

def number_of_bananas(monkey):
"""Returns number of bananas that monkey has."""
return monkey.bananas

print "number_of_bananas( FIRST MONKEY ): ", number_of_bananas(monkeys[0])

print

max_monkey = max(monkeys, key=number_of_bananas)


print "Max monkey: ", max_monkey

Output:

Random monkeys:

[Monkey with 2 bananas., Monkey with 39 bananas., Monkey with 15 bananas., Monkey with 26
bananas., Monkey with 10 bananas.]

number_of_bananas( FIRST MONKEY ): 2

20
9). 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)

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

Output:

The optimal value is : 5

22
10). Write a program to implement 8-Queens Problem using Python

N = 8 # (size of the chessboard)


def solveNQueens(board, col):
if col == N:
print(board)
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQueens(board, col + 1):
return True
board[i][col] = 0
return False

def isSafe(board, row, col):


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

23
board = [[0 for x in range(N)] for y in range(N)]
if not solveNQueens(board, 0):
print("No solution found")

Output:

[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0],

[0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0],

[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]]

24

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy