Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

PRACTICAL

FILE ON
Artificial Intelligence Lab
B.Tech CSE 6th sem
Course code: LC-CSE-326G
Session: 2022-23

Submitted To-
Submitted By-
Mrs. Simmi Madaan
Name- Tanmay Khandelwal
Assistant Professor CSE
Roll No.- 6th Semester
INDEX
S List of Programs Date Sign
.
N
o
1 Write a program to implement Tic-Tac-Toe
game using python
2 Write a python program to implement
simple Chatbot
3 Write a Program to Implement Depth First Search
using Python.
4 Write a python program to implement Breadth first
search Traversal.
5 Write a python program to implement Water
Jug Problem
6 Write a program to implement 8-puzzle
problem using python.
7 Write a Program to Implement Travelling
Salesman Problem using Python.
8 Write a python program to remove stop words for
a given passage from a text file using NLTK?
9 Write a python program to implement stemming
for a given sentence using NLTK?
10 Write a python program to POS (Parts of
Speech) tagging for the give sentence using
NLTK?
Program 1: Write a program to implement Tic-Tac-Toe
game using python.
Solution:
def print_board(board):
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---|---|---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---|---|---")
print(f" {board[6]} | {board[7]} | {board[8]} ")

def get_move(player):
valid_input = False
while not valid_input:
move = input(f"{player}, enter a number (1-9) to make a move: ")
if move.isdigit() and int(move) in range(1, 10):
return int(move) - 1
else:
print("Invalid input. Please enter a number between 1 and 9.")

def check_win(board):
# Check rows
for i in range(0, 9, 3):
if board[i] == board[i+1] == board[i+2] != " ":
return board[i]
# Check columns
for i in range(3):
if board[i] == board[i+3] == board[i+6] != " ":
return board[i]
# Check diagonals
if board[0] == board[4] == board[8] != " ":
return board[0]

if board[2] == board[4] == board[6] != " ":


return board[2]
# Check for a tie
if " " not in board:
return "Tie"
# Game is still ongoing
return None
def play_game():
board = [" "] * 9
players = ["X", "O"]
current_player = players[0]
print("Let's play Tic-Tac-Toe!")
while True:
print_board(board)
move = get_move(current_player)
if board[move] != " ":
print("That space is already taken. Please choose another.")
continue
board[move] = current_player
winner = check_win(board)
if winner:
print_board(board)
if winner == "Tie":
print("It's a tie!")
else:
print(f"{winner} wins!")
break
current_player = players[(players.index(current_player)+1) % 2]

play_game()
OUTPUT:
Program 2: Write a python program to implement simple
Chatbot
Solution:
import random

# Define a function to generate a random greeting

def greeting():
responses = ["Hi, My name is jackob!", "Hello, My name is jackob!",
"Hey, My name is jackob!"]
return random.choice(responses)

# Define a function to generate a response to a user input

def response(user_input):
responses = {
"hello": "How can i help you Sir/Mam",
"what is the url of meri website": "Here is the url of MERI Group of
Institutions https://meri.edu.in/",
"how to check the resutls mdu university": "You, can check it on
http://result.mdurtk.in/postexam/result.aspx",
"thanku": "Welcome, if you need to know anything just text hello!!",
"bye": "Goodbye!",
}
return responses.get(user_input.lower(), "I'm sorry, I don't understand
that.")

# Define the main chat loop

def chat():
print(greeting())
while True:
user_input = input("You: ")
if user_input.lower() == "bye":
print(response("bye"))
break
else:
print("Chatbot: " + response(user_input))

# Start the chat


chat()
Output:
Program 3: Write a Program to Implement Depth First
Search using Python.

Solution:

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
alpha = input('Enter the alphabet to be search[A,B,C,D,E,F]: ')
visited = set() # Set to keep track of visited nodes.

def dfs(visited, graph, node):


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

# Driver Code
dfs(visited, graph, alpha)
Output:
Program 4: Write a python program to implement Breadth
first search Traversal.

Solution:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
alpha = input('Enter the alphabet to be search[A,B,C,D,E,F]: ')
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue

def bfs(visited, graph, node):


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

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


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

# Driver Code
bfs(visited, graph, alpha)
Output:
Program 5: Write a python program to implement
Water Jug Problem?

Solution:
from collections import defaultdict

jug1, jug2, aim = 4, 3, 2

visited = defaultdict(lambda: False)

def waterJugSolver(amt1, amt2):


if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True

if visited[(amt1, amt2)] == False:


print(amt1, amt2)

visited[(amt1, amt2)] = True

return (waterJugSolver(0, amt2) or


waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1-amt1)), amt2 - min(amt2,
(jug1-amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2-amt2)), amt2 + min(amt1,
(jug2-amt2))))

else:
return False

print("Steps: ")
waterJugSolver(0, 0)
Output:
Program 6: Write a program to implement 8-puzzle
problem using python.

Solution:
import copy
from heapq import heappush, heappop

n=3

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

class priorityQueue:
def __init__(self):
self.heap = []

def push(self, k):


heappush(self.heap, k)

def pop(self):
return heappop(self.heap)

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

self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level

def __lt__(self, nxt):


return self.cost < nxt.cost
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:
new_mat = copy.deepcopy(mat)

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]

cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,


cost, level)
return new_node

def printMatrix(mat):

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

def isSafe(x, y):


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

def printPath(root):

if root == None:
return

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

def solve(initial, empty_tile_pos, final):

pq = priorityQueue()

cost = calculateCost(initial, final)


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

pq.push(root)

while not pq.empty():

minimum = pq.pop()

if minimum.cost == 0:

printPath(minimum)
return
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]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)

pq.push(child)

initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]

solve(initial, empty_tile_pos, final)


Output:
Program 7: Write a Program to Implement Travelling
Salesman Problem using Python.

Solution:
from sys import maxsize
from itertools import permutations
V=4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)

min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
# store current Path weight(cost)
current_pathweight = 0
# compute current path weight
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
# update minimum
min_path = min(min_path, current_pathweight)
return min_path

if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
Output:

You might also like