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

AI program codes 2023

Ai codes sppu

Uploaded by

parth92.6000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

AI program codes 2023

Ai codes sppu

Uploaded by

parth92.6000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

PROBLEM STATEMENT : Implement depth first search algorithm and Breadth First Search algorithm.

Use an undirected graph and develop a recursive algorithm for searching all the vertices of a graph or
tree data structure.
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
PROBLEM STATEMENT : Implement a solution for a Constraint Satisfaction Problem using Branch and
Bound and Backtracking for n-queens problem or a graph coloring problem.

# Constraint Satisfaction Problem for Graph Coloring

colors = ['Red', 'Blue', 'Green', 'Yellow', 'Black']


states = ['Andhra', 'Karnataka', 'TamilNadu', 'Kerala']
neighbors = {}
neighbors['Andhra'] = ['Karnataka', 'TamilNadu']
neighbors['Karnataka'] = ['Andhra', 'TamilNadu', 'Kerala']
neighbors['TamilNadu'] = ['Andhra', 'Karnataka', 'Kerala']
neighbors['Kerala'] = ['Karnataka', 'TamilNadu']
colors_of_states = {}
def promising(state, color):
for neighbor in neighbors.get(state):
color_of_neighbor = colors_of_states.get(neighbor)
if color_of_neighbor == color:
return False
return True
def get_color_for_state(state):
for color in colors:
if promising(state, color):
return color
def main():
for state in states:
colors_of_states[state] = get_color_for_state(state)
print( colors_of_states)
main()

OUTPUT :
{'Andhra': 'Red', 'Karnataka': 'Blue', 'TamilNadu': 'Blue', 'Kerala': 'Red
'}
PROBLEM STATEMENT : Implement Greedy search algorithm for any of the following application:
• Selection Sort

# Greedy Algorithm (Selection sort)

def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

OUTPUT :

Enter the list of numbers: 5 1 4 2 3


Sorted list: [1, 2, 3, 4, 5]
PROBLEM STATEMENT : Develop an elementary chatbot for any suitable customer interaction
application

# Chatbot
from tkinter import *
root = Tk()
root.title("Chatbot")
def send():
send = "\nYou : "+e.get()
txt.insert(END, send)
user = e.get().lower()
if(user == "hello"):
txt.insert(END, "\nBot : Hi\n")
elif(user == "hi" or user == "hii" or user == "hiiii"):
txt.insert(END, "\nBot : Hello\n")
elif(e.get() == "how are you"):
txt.insert(END, "\nBot : fine! and you")
elif(user == "fine" or user == "i am good" or user == "i am doing good"):
txt.insert(END,"\nBot : Great! how can I help you.")
else:
txt.insert(END,"\nBot : Sorry! I dind't got you")
e.delete(0, END)
txt = Text(root)
txt.grid(row=0, column=0, columnspan=2)
e = Entry(root, width=100)
e.grid(row=1, column=0)
send = Button(root, text="Send", command=send).grid(row=1, column=1)
root.mainloop()

OUTPUT:
You : HII
Bot : Hello
You : how are you?
Bot : Sorry! I dind't got you
You : how are you
Bot : fine! and you
You : i am good
Bot : Great! how can I help you.
PROBLEM STATEMENT : Implement A star (A*) Algorithm for any game search problem.

import random
class TicTacToe:
def __init__(self):
self.board = []
def create_board(self):
for i in range(3):
row = []
for j in range(3):
row.append('-')
self.board.append(row)
def get_random_first_player(self):
return random.randint(0, 1)
def fix_spot(self, row, col, player):
self.board[row][col] = player
def is_player_win(self, player):
win = None
n = len(self.board)
# checking rows
for i in range(n):
win = True
for j in range(n):
if self.board[i][j] != player:
win = False
break
if win:
return win
# checking columns
for i in range(n):
win = True
for j in range(n):
if self.board[j][i] != player:
win = False
break
if win:
return win
# checking diagonals
win = True
for i in range(n):
if self.board[i][i] != player:
win = False
break
if win:
return win
win = True
for i in range(n):
if self.board[i][n - 1 - i] != player:
win = False
break
if win:
return win
return False
for row in self.board:
for item in row:
if item == '-':
return False
return True
def is_board_filled(self):
for row in self.board:
for item in row:
if item == '-':
return False
return True
def swap_player_turn(self, player):
return 'X' if player == 'O' else 'O'
def show_board(self):
for row in self.board:
for item in row:
print(item, end=" ")
print()
def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
while True:
print(f"Player {player} turn")
self.show_board()
# taking user input
row, col = list(
map(int, input("Enter row and column numbers to fix spot:
").split()))
print()
# fixing the spot
self.fix_spot(row - 1, col - 1, player)
# checking whether current player is won or not
if self.is_player_win(player):
print(f"Player {player} wins the game!")
break
# checking whether the game is draw or not
if self.is_board_filled():
print("Match Draw!")
break
# swapping the turn
player = self.swap_player_turn(player)
# showing the final view of board
print()
self.show_board()
# starting the game
tic_tac_toe = TicTacToe()
tic_tac_toe.start()

OUTPUT :
Player X turn
- - -
- - -
- - -
Enter row and column numbers to fix spot: 2 3

Player O turn
- - -
- - X
- - -
Enter row and column numbers to fix spot: 3 2

Player X turn
- - -
- - X
- O -
Enter row and column numbers to fix spot: 1 2

Player O turn
- X -
- - X
- O -
Enter row and column numbers to fix spot: 3 3

Player X turn
- X -
- - X
- O O
Enter row and column numbers to fix spot: 1 3

Player O turn
- X X
- - X
- O O
Enter row and column numbers to fix spot: 3 1

Player O wins the game!

- X X
- - X
O O O
PROBLEM STATEMENT : Implement Alpha-Beta Tree search for any game search problem.

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

OUTPUT :
The optimal value is : 5

You might also like