0% found this document useful (0 votes)
8 views8 pages

Python AI Lab Programs Overview

The document outlines various Python programming lab programs focused on artificial intelligence concepts, including games like Tic-Tac-Toe and Nim, algorithms like A* and Alpha-Beta pruning, fuzzy set operations, and a simple chatbot. Each program includes code snippets demonstrating the implementation of the respective concepts. Additionally, there are examples of arithmetic calculations in Prolog and a crossword puzzle generator.

Uploaded by

rahulsinguwari0
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)
8 views8 pages

Python AI Lab Programs Overview

The document outlines various Python programming lab programs focused on artificial intelligence concepts, including games like Tic-Tac-Toe and Nim, algorithms like A* and Alpha-Beta pruning, fuzzy set operations, and a simple chatbot. Each program includes code snippets demonstrating the implementation of the respective concepts. Additionally, there are examples of arithmetic calculations in Prolog and a crossword puzzle generator.

Uploaded by

rahulsinguwari0
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

PRINCIPLES OF ARTIFICIAL INTELLIGENCE

LAB PROGRAMS
Program 1 :

Design and implement Tic-Tac-Toe game using Python programming

import random

def print_board(board):
print(" 1 2 3 ")
for i in range(3):
print(f"{i+1}{' '.join(board[i])}")

def check_winner(board, player):


for row in board:
if all(cell==player for cell in row):
return True
for col in range(3):
if all(board[row][col]==player for row in range(3)):
return True
if all(board[i][i]==player for i in range(3)) or all(board[i][2-i]==player for i in range(3)):
return True
return False

def is_board_full(board):
return all(cell!=''for row in board for cell in row)

def get_available_moves(board):
return [(i,j) for i in range(3) for j in range(3) if board[i][j]=='']

def player_move(board):
while True:
try:
row,col=map(int,input("Enter your move(row and column, e.g., 1 2): ").split())
if 1<=row<=3 and 1<=col<=3 and board[row-1][col-1]=='':
return row-1,col-1
else:
print("Invalid move. Try again!")
except ValueError:
print("Invalid input. Please enter two space separated integers")

def computer_move(board,computer,player):
available_moves=get_available_moves(board)
for move in available_moves:
board[move[0]][move[1]]=computer
if check_winner(board,computer):
return move
board[move[0]][move[1]]=''

for move in available_moves:


board[move[0]][move[1]]=player
if check_winner(board,player):
board[move[0]][move[1]]=computer
return move
board[move[0]][move[1]]=''

return [Link](available_moves)

def play_game():
board=[[''for i in range(3)]for j in range(3)]
player='X'
computer='O'
while True:
print_board(board)
if check_winner(board,player):
print("Congratulations! You Win!!")
break
elif check_winner(board,computer):
print("Computer Wins!!")
break
elif is_board_full(board):
print("It's a Tie!!")
break
if player=='X':
row,col=player_move(board)
board[row][col]='X'
player='O'
computer='X'
else:
row,col=computer_move(board,computer,player)
board[row][col]='O'
player='X'
computer='O'

if __name__=="__main__":
play_game()

Program 2 :

Demonstrate Nim game using Python programming

import random

def print_board(heap):
print(f"Current heap : {'|'*heap} ")

def get_user_move(heap):
while True:
try:
sticks_to_remove = int(input(f"Enter the no. to remove (minimum 1,maximum {min(heap,heap/2)}):
"))
if 1<=sticks_to_remove<=min(heap,heap//2):
break
else:
print(f"Invalid [Link] sticks. Please enter a no. between 1 and {min(heap,heap//2)}")
except ValueError:
print(f"Invalid input. Please enter a valid number")
return sticks_to_remove

def get_computer_move(heap):
xor_sum=heap
for i in range(heap):
xor_sum^=i
if xor_sum==0:
max_sticks=min(heap,heap//2)
sticks_to_remove=[Link](1,max_sticks)
else:
max_sticks=min(heap//2,heap)
sticks_to_remove=max(1,min(max_sticks,heap-xor_sum))
return sticks_to_remove

def nim_game():
heap=16
player_turn=1
while heap>1:
print_board(heap)
if player_turn==1:
player_name="Player 1"
sticks_to_remove=get_user_move(heap)
else:
player_name="Computer"
sticks_to_remove=get_computer_move(heap)
heap-=sticks_to_remove
print(f"{player_name} removes {sticks_to_remove} sticks")
player_turn=3-player_turn
print_board(heap)
Winner="Player 1" if player_turn==2 else "Computer"
print(f"{player_name} picks the last stick")

if __name__=="__main__":
nim_game()

Program 3 :

Write a Python programming to implement A* Algorithm

def aStarAlgo(start_node,stop_node):
open_set=set([start_node])
closed_set=set()
g={}
parents={}

g[start_node]=0
parents[start_node]=start_node
while len(open_set)>0:
n=None
for v in open_set:
if n==None or g[v]+heuristic(v)<g[n]+heuristic(n):
n=v
if n==stop_node or Graph_nodes[n]==None:
pass
else:
for(m,weight) in get_neighbours(n):
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m]=n
g[m]=g[n]+weight
else:
if g[m]>g[n]+weight:
g[m]=g[n]+weight
parents[m]=n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)

if n==None:
print("Path doesn't exist!")
return None
if n==stop_node:
path=[]
while parents[n]!=n:
[Link](n)
n=parents[n]
[Link](start_node)
[Link]()
print('Path found:{} '.format(path))
return path
open_set.remove(n)
closed_set.add(n)
print("Path does not exist!")
return None

def get_neighbours(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None

def heuristic(n):
H_dist={
'A':10,
'B':8,
'C':5,
'D':7,
'E':3,
'F':6,
'G':5,
'H':3,
'I':1,
'J':0
}
return H_dist[n]

Graph_nodes = {
'A':[('B',6),('F',3)],
'B':[('C',3),('D',2)],
'C':[('D',1),('E',5)],
'D':[('E',8)],
'E':[('I',5),('J',5)],
'F':[('G',1),('H',7)],
'G':[('I',3)],
'H':[('I',2)],
'I':[('J',3)]
}
aStarAlgo('A','J')

Program 4 :

Write a Python programming to demonstrate working of Alpha-Beta Pruning

import math

#Represents the game tree node


class Node:
def __init__(self,value=None):
[Link]=value
[Link]=[]
#Minimax algorithm with alpha-beta pruning
def minimax_alpha_beta(node,depth,alpha,beta,maximizingPlayer):
if depth==0 or len([Link])==0:
return [Link]

if maximizingPlayer:
value=-[Link]
for child in [Link]:
value=max(value,minimax_alpha_beta(child,depth-1,alpha,beta,False))
alpha=max(alpha,value)
if alpha>=beta:
break
return value

else:
value=[Link]
for child in [Link]:
value=min(value,minimax_alpha_beta(child,depth-1,alpha,beta,True))
beta=min(beta,value)
if beta<=alpha:
break
return value

#Example tree
if __name__=="__main__":

#Constructing a simple game tree


root=Node()
[Link]=3

node1=Node()
[Link]=5
[Link](node1)

node2=Node()
[Link]=6
[Link](node2)

node3=Node()
[Link]=9
[Link](node3)

node4=Node()
[Link]=1
[Link](node4)

node5=Node()
[Link]=2
[Link](node5)

node6=Node()
[Link]=0
[Link](node6)

#Perform minimax with alpha-beta pruning


result=minimax_alpha_beta(root,3,-[Link],[Link],True)
print("Optimal value : ",result)
Program 5 :

Demonstrate Union and Intersection of two Fuzzy Sets using Python programming

def fuzzy_union(set1,set2):
union_result={}
all_keys=set([Link]()).union([Link]())
for key in all_keys:
union_result[key]=max([Link](key,0),[Link](key,0))
return union_result

def fuzzy_intersection(set1,set2):
intersection_result={}
common_keys=set([Link]()).intersection([Link]())
for key in common_keys:
intersection_result[key]=min(set1[key],set2[key])
return intersection_result

def input_fuzzy_set():
fuzzy_set={}
n=int(input("Enter the number of elements in the fuzzy set:"))
for _ in range(n):
element=input("Enter element name:")
membership_value=float(input(f"Enter membership value for {element} :"))
fuzzy_set[element]=membership_value
return fuzzy_set

print("Input Fuzzy Set A:")


fuzzy_set_A=input_fuzzy_set()
print("\nInput Fuzzy Set B:")
fuzzy_set_B=input_fuzzy_set()
union_result=fuzzy_union(fuzzy_set_A,fuzzy_set_B)
intersection_result=fuzzy_intersection(fuzzy_set_A,fuzzy_set_B)
print("\nUnion of Fuzzy Sets A and B:",union_result)
print("\nIntersection Fuzzy Sets A and B:",intersection_result)

Program 6 :

Write a program in Prolog to implement simple arithmetic calculations

%Addition
add(X,Y,Result) :-
Result is X + Y.

% Subtraction
subtract(X,Y,Result) :-
Result is X - Y.

% Multiplication
multiply(X,Y,Result) :-
Result is X * Y.

% Division
divide(X,Y,Result) :-
Y =\= 0, %Ensure Y is not zero to avoid division by zero error
Result is X / Y.

Program 7 :

Design and implement Crossword Puzzle using Python programming


import random
class Crossword:
def __init__(self,height,width):
[Link]=height
[Link]=width
[Link]=[[' 'for _ in range(width)]for _ in range(height)]
[Link]=[]

def add_word(self,word):
word=[Link]()
if len(word)>max([Link],[Link]):
print(f"Word'{word} is too long to fit in the grid")
return
[Link](word)
placed=False
while not placed:
direction=[Link](['across','down'])
if direction=='across':
x=[Link](0,[Link]-len(word))
y=[Link](0,[Link]-1)
if self.check_fit(word,x,y,1,0):
self.place_word(word,x,y,1,0)
placed=True
else:
x=[Link](0,[Link]-1)
y=[Link](0,[Link]-len(word))
if self.check_fit(word,x,y,0,1):
self.place_word(word,x,y,0,1)
placed=True
def check_fit(self,word,x,y,dx,dy):
for i in range(len(word)):
if [Link][y][x] not in [' ', word[i]]:
return False
x+=dx
y+=dy
return True
def place_word(self,word,x,y,dx,dy):
for i in range(len(word)):
[Link][y][x]=word[i]
x+=dx
y+=dy
def display(self):
for row in [Link]:
print(' '.join(row))
def main():
crossword=Crossword(12,12)
words=["SAHYADRI","COLLEGE","ENGINEERING","MANAGEMENT","ADYAR"]
for word in words:
crossword.add_word(word)
[Link]()
if __name__=="__main__":
main()

Program 8 :

Demonstrate a simple ChatBot with minimum 10 conversations

import random

responses = {
"hi" : ["Hello!","Hi there!","Hey!"],
"how are you" : ["I'm doing well, thankyou","I'm great, thanks for asking!"],
"what's your name" : ["I'm a Chatbot!","You can call me Chatbot"],
"what do you do?" : ["I'm here to chat with you!","I'm a conversational agent"],
"bye" : ["Good bye!","See you later!","Bye! Have a great day!"],
"tell me a joke" : ["Why don't scientists trust atoms? Because they makeup everything!",
"I'm not good at jokes,but here's one: Why was math book sad? Because it had too many
problems"],
"who created you?" : ["I was created by a team of developers",
"My creators prefer to remain anonymous"],
"what is the weather today" : ["I'm sorry I can't provide realtime information",
"You can check the weather on a weather website or app"],
"how old are you?" : ["I don't have an age.I'm just a program","I exist in the realm of ones and zeroes
so I don't age"],
"what is the meaning of life?" : ["The meaning of life is a philosophical question that has puzzled
human for centuries",
"I think the meaning of life is subjective and varies from person to person"]
}

def get_response(user_input):
if user_input.lower() in responses:
return [Link](responses[user_input.lower()])
else:
return "I'm sorry, I don't understand that"

def main():
print("Welcome to the Chat Bot!")
print("You can start chatting. Type 'bye' to exit")
while True:
user_input = input("You : ")
if user_input.lower() == 'bye':
print(get_response(user_input))
break
else:
print("ChatBot : ", get_response(user_input))

if __name__ == "__main__":
main()

You might also like