0% found this document useful (0 votes)
76 views29 pages

AI

The document describes algorithms for solving various graph problems and puzzles using Python code. It includes implementations of breadth-first search, depth-first search, the Tower of Hanoi puzzle, A* search, the N-Queens problem, alpha-beta pruning, and the Water Jug problem. Python code is provided showing how to represent graphs and trees and solve problems by traversing the structures.

Uploaded by

Rahul Masam
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)
76 views29 pages

AI

The document describes algorithms for solving various graph problems and puzzles using Python code. It includes implementations of breadth-first search, depth-first search, the Tower of Hanoi puzzle, A* search, the N-Queens problem, alpha-beta pruning, and the Water Jug problem. Python code is provided showing how to represent graphs and trees and solve problems by traversing the structures.

Uploaded by

Rahul Masam
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/ 29

ARTIFICIAL INTELLIGENCE PRACTICALS 1

BFS

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 2

from collections import defaultdict

class Graph:

def __init__(self):

self.graph = defaultdict(list)

def addEdge(self,u,v):

self.graph[u].append(v)

def BFS(self, s):

visited = [False] * (len(self.graph))

queue = []

queue.append(s)

visited[s] = True

while queue:

s = queue.pop(0)

print (s, end = " ")

for i in self.graph[s]:

if visited[i] == False:

queue.append(i)

visited[i] = True

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)

print ("Following is Breadth First Traversal"

" (starting from vertex 2)")

g.BFS(2)

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 3

DFS

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 4

from collections import defaultdict

class Graph:

def __init__(self):

self.graph = defaultdict(list)

def addEdge(self,u,v):

self.graph[u].append(v)

def DFSUtil(self,v,visited):

visited[v]= True

print (v)

for i in self.graph[v]:

if visited[i] == False:

self.DFSUtil(i, visited)

def DFS(self,v):

visited = [False]*(len(self.graph))

self.DFSUtil(v,visited)

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)

print ("Following is DFS from (starting from vertex 2)")

g.DFS(2)

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 5

Hanoi

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 6

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

if n == 1:

print ("Move disk 1 from rod",from_rod,"to rod",to_rod)

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=4

TowerOfHanoi(n , "A","B","C")

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 7

A* & AO* algorithm

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 8

Note: Install 2 package in python scripts directory using pip command.


1. pip install simpleai
2. pip install pydot flask

from simpleai.search import SearchProblem, astar


GOAL = ‘HELLO WORLD’
class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(‘ ABCDEFGHIJKLMNOPQRSTUVWXYZ’)
else:
return []
def result(self, state, action):
return state + action

def is_goal(self, state):


return state == GOAL
def heuristic(self, state):
# how far are we from the goal?
Wrong = sum([1 if state[i] != GOAL[i] else 0
for I in range(len(state))])
missing = len(GOAL) – len(state)
return wrong + missing
problem = HelloProblem(initial_state=’’)
result = astar(problem)
print(result.state)
print(result.path())

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 9

N_Queen Problem

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 10

class QueenChessBoard:

def __init__(self, size):

# board has dimensions size x size

self.size = size

# columns[r] is a number c if a queen is placed at row r and column c.

# columns[r] is out of range if no queen is place in row r.

# Thus after all queens are placed, they will be at positions

# (columns[0], 0), (columns[1], 1), ... (columns[size - 1], size - 1)

self.columns = []

def place_in_next_row(self, column):

self.columns.append(column)

def remove_in_current_row(self):

return self.columns.pop()

def is_this_column_safe_in_next_row(self, column):

# index of next row

row = len(self.columns)

# check column

for queen_column in self.columns:

if column == queen_column:

return False

# check diagonal

for queen_row, queen_column in enumerate(self.columns):

if queen_column - queen_row == column - row:

return False

# check other diagonal

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 11

for queen_row, queen_column in enumerate(self.columns):

if ((self.size - queen_column) - queen_row

== (self.size - column) - row):

return False

return True

def display(self):

for row in range(self.size):

for column in range(self.size):

if column == self.columns[row]:

print('Q', end=' ')

else:

print('.', end=' ')

print()

def solve_queen(size):

"""Display a chessboard for each possible configuration of placing n queens

on an n x n chessboard and print the number of such configurations."""

board = QueenChessBoard(size)

number_of_solutions = 0

row = 0

column = 0

# iterate over rows of board

while True:

# place queen in next row

while column < size:

if board.is_this_column_safe_in_next_row(column):

board.place_in_next_row(column)

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 12

row += 1

column = 0

break

else:

column += 1

# if could not find column to place in or if board is full

if (column == size or row == size):

# if board is full, we have a solution

if row == size:

board.display()

print()

number_of_solutions += 1

# small optimization:

# In a board that already has queens placed in all rows except

# the last, we know there can only be at most one position in

# the last row where a queen can be placed. In this case, there

# is a valid position in the last row. Thus we can backtrack two

# times to reach the second last row.

board.remove_in_current_row()

row -= 1

# now backtrack

try:

prev_column = board.remove_in_current_row()

except IndexError:

# all queens removed

# thus no more possible configurations

break

# try previous row again

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 13

row -= 1

# start checking at column = (1 + value of column in previous row)

column = 1 + prev_column

print('Number of solutions:', number_of_solutions)

n = int(input('Enter n: '))

solve_queen(n)

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 14

alpha_beta

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 15

tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]

root = 0

pruned = 0

def children(branch, depth, alpha, beta):

global tree

global root

global pruned

i=0

for child in branch:

if type(child) is list:

(nalpha, nbeta) = children(child, depth + 1, alpha, beta)

if depth % 2 == 1:

beta = nalpha if nalpha < beta else beta

else:

alpha = nbeta if nbeta > alpha else alpha

branch[i] = alpha if depth % 2 == 0 else beta

i += 1

else:

if depth % 2 == 0 and alpha < child:

alpha = child

if depth % 2 == 1 and beta > child:

beta = child

if alpha >= beta:

pruned += 1

break

if depth == root:

tree = alpha if root == 0 else beta

return (alpha, beta)

def alphabeta(in_tree=tree, start=root, lower=-15, upper=15):

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 16

global tree

global pruned

global root

(alpha, beta) = children(tree, start, lower, upper)

if __name__ == "__main__":

print ("(alpha, beta): ", alpha, beta)

print ("Result: ", tree)

print ("Times pruned: ", pruned)

return (alpha, beta, tree, pruned)

if __name__ == "__main__":

alphabeta()

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 17

Water Jug Problem

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 18

def pour(jug1, jug2):

max1, max2, fill = 5, 7, 4 #Change maximum capacity and final capacity

print("%d\t%d" % (jug1, jug2))

if jug2 is fill:

return

elif jug2 is max2:

pour(0, jug1)

elif jug1 != 0 and jug2 is 0:

pour(0, jug1)

elif jug1 is fill:

pour(jug1, 0)

elif jug1 < max1:

pour(max1, jug2)

elif jug1 < (max2-jug2):

pour(0, (jug1+jug2))

else:

pour(jug1-(max2-jug2), (max2-jug2)+jug2)

print("JUG1\tJUG2")

pour(0, 0)

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 19

Tic Tac Toe

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 20

from __future__ import print_function

choices = []

for x in range (0, 9) :

choices.append(str(x + 1))

playerOneTurn = True

winner = False

def printBoard() :

print( '\n -----')

print( '|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')

print( ' -----')

print( '|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')

print( ' -----')

print( '|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')

print( ' -----\n')

while not winner :

printBoard()

if playerOneTurn :

print( "Player 1:")

else :

print( "Player 2:")

try:

choice = int(input(">> "))

except:

print("please enter a valid field")

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 21

continue

if choices[choice - 1] == 'X' or choices [choice-1] == 'O':

print("illegal move, plase try again")

continue

if playerOneTurn :

choices[choice - 1] = 'X'

else :

choices[choice - 1] = 'O'

playerOneTurn = not playerOneTurn

for x in range (0, 3) :

y=x*3

if (choices[y] == choices[(y + 1)] and choices[y] == choices[(y + 2)]) :

winner = True

printBoard()

if (choices[x] == choices[(x + 3)] and choices[x] == choices[(x + 6)]) :

winner = True

printBoard()

if((choices[0] == choices[4] and choices[0] == choices[8]) or

(choices[2] == choices[4] and choices[4] == choices[6])) :

winner = True

printBoard()

print ("Player " + str(int(playerOneTurn + 1)) + " wins!\n")

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 22

Shuffle Deck of Cards

import itertools, random

# make a deck of cards

deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards

random.shuffle(deck)

# draw five cards

print("You got:")

for i in range(5):

print(deck[i][0], "of", deck[i][1])

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 23

World problem

from __future__ import print_function

from simpleai.search import (CspProblem, backtrack, min_conflicts,


MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE,LEAST_CONSTRAINING_VALUE)

variables = ('WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T')

domains = dict((v, ['red', 'green', 'blue']) for v in variables)

def const_different(variables, values):

return values[0] != values[1] # expect the value of the neighbors to be different

constraints = [

(('WA', 'NT'), const_different),

(('WA', 'SA'), const_different),

(('SA', 'NT'), const_different),

(('SA', 'Q'), const_different),

(('NT', 'Q'), const_different),

(('SA', 'NSW'), const_different),

(('Q', 'NSW'), const_different),

(('SA', 'V'), const_different),

(('NSW', 'V'), const_different),

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 24

my_problem = CspProblem(variables, domains, constraints)

print(backtrack(my_problem))

print(backtrack(my_problem,

variable_heuristic=MOST_CONSTRAINED_VARIABLE))

print(backtrack(my_problem,

variable_heuristic=HIGHEST_DEGREE_VARIABLE))

print(backtrack(my_problem,

value_heuristic=LEAST_CONSTRAINING_VALUE))

print(backtrack(my_problem,

variable_heuristic=MOST_CONSTRAINED_VARIABLE,

value_heuristic=LEAST_CONSTRAINING_VALUE)s)

print(backtrack(my_problem,

variable_heuristic=HIGHEST_DEGREE_VARIABLE,

value_heuristic=LEAST_CONSTRAINING_VALUE))

print(min_conflicts(my_problem))

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 25

Code for Alpha beta search

# 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

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 26

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

The optimal value is : 5

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 27

Traveling salesman problem code

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 28

// CPP program to implement traveling salesman

// problem using naive approach.

#include <bits/stdc++.h>

using namespace std;

#define V 4

// implementation of traveling Salesman Problem

int travllingSalesmanProblem(int graph[][V], int s)

// store all vertex apart from source vertex

vector<int> vertex;

for (int i = 0; i < V; i++)

if (i != s)

vertex.push_back(i);

// store minimum weight Hamiltonian Cycle.

int min_path = INT_MAX;

do {

// store current Path weight(cost)

int current_pathweight = 0;

// compute current path weight

int k = s;

for (int i = 0; i < vertex.size(); i++) {

current_pathweight += graph[k][vertex[i]];

k = vertex[i];

current_pathweight += graph[k][s];

// update minimum

TYBSCIT 17038 HARSHITA SALIAN


ARTIFICIAL INTELLIGENCE PRACTICALS 29

min_path = min(min_path, current_pathweight);

} while (next_permutation(vertex.begin(), vertex.end()));

return min_path;

// driver program to test above function

int main()

// matrix representation of graph

int graph[][V] = { { 0, 10, 15, 20 },

{ 10, 0, 35, 25 },

{ 15, 35, 0, 30 },

{ 20, 25, 30, 0 } };

int s = 0;

cout << travllingSalesmanProblem(graph, s) << endl;

return 0;

TYBSCIT 17038 HARSHITA SALIAN

You might also like