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

AI Lab Final

Uploaded by

King Lord
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)
6 views

AI Lab Final

Uploaded by

King Lord
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/ 22

G. L.

Bajaj Group of Institutions, Mathura


Department of Computer Science & Engineering

PRACTICAL FILE
Artificial Intelligence Lab

(KAI-551)

SESSION: ODD Sem 2023-24

Submitted By: Submitted To:


Name: Name: Er. Harsh Sanger

Roll. No. Designation: Asst. Professor

Year: 3rd

Sem: 5
INDEX

S. No. List of Experiments Page No. Date Sign


1 Write a python program to implement breadth First search 3
traversal?
2 Write a python program to implement water jug problem? 15
3 Write a python program to remove punctuations from the 17
given string?

4 Write a python program to sort the sentence in alphabetical 19


order?

5 Write a program to implement hangman game using python. 21

6 Write a program to implement tic-Tac-Toe game using 23


python.

7 Write a python program to remove stopwords for a given 24


passage from a textfile using nltk?

8 Write a python program to implements temming for a given 25


sentence using nltk?

9 Write a python program to pos(Partsof Speech) tagging for the 26


give sentence using NLTK?

10 Write a python program to implement lemmatization 27


using nltk?
11 Write a python program for text classification for the give 29
sentence using nltk.
Experiment no. – 01

Objective: Write a python program to implement breadth First search traversal?

class Graph:

def __init__(self):

self.graph = defaultdict(list)

def add_edge(self, u, v):

self.graph[u].append(v)

def bfs(self, s):

visited = [False] * (max(self.graph) + 1)

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.add_edge(0, 1)

g.add_edge(0, 2)

g.add_edge(1, 2)

g.add_edge(2, 0)

g.add_edge(2, 3)

g.add_edge(3, 3)

print("Following is Breadth First Traversal (starting from vertex 2)")

g.bfs(2)
Output:
Following is breadth first traversal (starting from vertex 2)
>3
20313
>
Experiment no. – 02

Objective: Write a python program to implement water jug problem?

From collection simport default dict

#and aimis the amount of water to be


measured.jug1,jug2,aim=4,3,2
Visited=defaultdict(lambda:false)

Def waterjugsolver(amt1,amt2):

If(amt1==aimandamt2==0)or(amt2==aimandamt1==0):print(amt1,am
t2)
Return true

ifvisited[(amt1,amt2)]==false:
Print(amt1,amt2)

visited[(amt1,amt2)]=true

return(waterjugsolver(0,amt2)or
Waterjugsolver(amt1,0)orwaterjugsolver(jug1,a
mt2)orwaterjugsolver(amt1,jug2)orwaterjugsolv
er(amt1+min(amt2,(jug1-amt1)),amt2-
min(amt2,(jug1-amt1)))orwaterjugsolver(amt1-
min(amt1, (jug2-amt2)),amt2+min(amt1,(jug2-
amt2))))
Else:
Returnfalse
Print("steps:")

waterjugsolver(0,0)
Output:
Steps:
00
40
43
03
30
33
42
02
Experiment no. – 03
Objective: write a python program to remove punctuations from the given string?

# define punctuation
Punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
My_str = "hello!!!, he said ---and went."#
To take input from the user
# my_str = input("enter a string: ")
# remove punctuation from the stringno_punct = ""
For char in my_str:
If char not in punctuations:
No_punct = no_punct + char
# display the unpunctuated string
Print(no_punct)

Output:
Hello he said and went
Experiment no. – 04
Objective: Write a python program to sort the sentence in alphabetical order?

# program to sort alphabetically the words form a string provided by the user
# change this value for a different result
My_str = "hello this is an example with cased letters"
# uncomment to take input from the user
#my_str = input("enter a string: ")
# breakdown the string into a list of words
Words = my_str.split()
#print(words)
# sort the listwords.sort()
# display the sorted words
Print("the sorted words are:")
For word in words:
Print(word)

Output:
The sorted words are:
Example
Hello
Is
With
An
Cased
Letters
This
Experiment no. – 05
Objective: Write a program to implement hangman game using python.

Description: hangman is a classic word-guessing game. The user should guess the word correctly by
entering alphabets of the user choice. The program will get input as single alphabet from the user and it
will matchmaking with the alphabets in the original word. If the user given alphabet matches with the
alphabet from the original word, then user must guess the remaining alphabets. Once the user successfully
found the word he will be declared as winner otherwise user lose the game.

Code
Def get available letters(letters guessed):
'''
Letters guessed: list, what letters have been guessed so far
Returns: string, comprised of letters that represents what letters have notyet been guessed.
'''
Import string
Fullstring = string.ascii_lowercase
Lettersleft = ''
For letter in fullstring:
If letter not in lettersguessed:
Lettersleft = lettersleft + letter
Return lettersleft
Def getguessedword(secretword, lettersguessed):
'''
Secretword: string, the word the user is guessing
Lettersguessed: list, what letters have been guessed so far
Returns: string, comprised of letters and underscores that represents
What letters in secretword have been guessed so far.
'''
Wordguessed = ''
For letter in secretword:
If letter in lettersguessed:
Wordguessed = wordguessed + letter
Else:
Wordguessed = wordguessed + '_ '
Return wordguessed
Def iswordguessed(secretword, lettersguessed)
'''
Secretword: string, the word the user is guessing
Lettersguessed: list, what letters have been guessed so far
Returns: boolean, true if all the letters of secretword are in lettersguessed;
False otherwise
'''
Numcorrect = 0
For letter in secretword:
If letter in lettersguessed:
Numcorrect += 1
Else:
Return false
Return true
Def hangman(secretword):
Guessesleft = 8
Lettersguessed =[]
Print('welcome to the game hangman!')
Print('i am thinking of a word that is ' + str(len(secretword)) + ' letters long.' )
Print('-----------')
While guessesleft > 0:
If iswordguessed(secretword, lettersguessed):
Return print('congratulations, you won!')
Print('you have ' + str(guessesleft) + ' guesses left.')
Print('available letters: ' + getavailableletters(lettersguessed))
User_input = input('please guess a letter: ')
User_input = str(user_input)
User_input = user_input.lower()
If user_input not in lettersguessed:
Lettersguessed.append(user_input)
If user_input in secretword:
Print("good guess: " + getguessedword(secretword, lettersguessed))
Print('-----------')
Else:
Print("oops! That letter is not in my word: " + getguessedword(secretword,lettersguessed))
Print('-----------')
Guessesleft -= 1
Else:
Print("oops! You've already guessed that letter: " + getguessedword(secretword,lettersguessed))
Print('-----------')
Return print("sorry, you ran out of guesses. The word was " + str(secretword))hangman('apple')

Output:
Welcome to the game hangman!
I am thinking of a word that is 5 letters long.
-----------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Good guess: a_ _ _ _
-----------
You have 8 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: p
Good guess: app_ _
-----------
You have 8 guesses left.
Available letters: bcdefghijklmnoqrstuvwxyz
Please guess a letter: p
Oops! You've already guessed that letter: app_ _
-----------
You have 8 guesses left.
Available letters: bcdefghijklmnoqrstuvwxyz
Please guess a letter: l
Good guess: appl_
-----------
You have 8 guesses left.
Available letters: bcdefghijkmnoqrstuvwxyz
Please guess a letter: e
Good guess: apple
-----------
Congratulation, you won!
Experiment no. – 06
Objective: writea program to implement tic-tac-toe game using python.

Defcreate_board():
Return(np.array([[0,0,0],
[0, 0,0],
[0, 0, 0]]))
# check for empty places on board
Defpossibilities(board):
L = []
For i in
range(len(board)):forjinra
nge(len(board)):
If board[i][j] ==
0:l.append((i,j))
Return(l)

# select a random place for the player


Defrandom_place(board, player):
Selection =
possibilities(board)current_loc =
random.choice(selection)board[current
_loc] = playerreturn(board)

# checks whether the player has


three# of their marks in a horizontal
row
Defrow_win(board, player):
For x in
range(len(board)):win=
true
For y in
range(len(board)):ifboa
rd[x, y]!=player:
Win =
falsecontin
ue
If win ==
true:return(
win)
Return(win)
# checks whether the player has
three#of their marksin avertical row
Def col_win(board,
player):forxinrange(len(bo
ard)):
Win=true
For y in
range(len(board)):ifboar
d[y][x]!=player:
Win =
falsecontin
ue
If win ==
true:return(
win)
Return(win)

Def diag_win(board,
player):win=true
Y=0
For x in
range(len(board)):ifboa
rd[x,x]!=player:
Win =
falseif win:
Return
winwin=true
if win:
For x in
range(len(board)):y=le
n(board)-1-x
If board[x, y] !=
player:win=false
Returnwin

Def
evaluate(board):
winner=0
Forplayer in[1, 2]:
If (row_win(board, player)
orcol_win(board,player)
ordiag_win(board,player)):
Winner=player
If np.all(board != 0) and winner ==
0:winner=-1
Return winner

# main function to start the game


Defplay_game():
Board, winner, counter = create_board(), 0,
1print(board)
Sleep(2)
While winner ==
0:forplayerin[1,2]:
Board = random_place(board,
player)print("board after " + str(counter) + "
move")print(board)
Sleep(2)count
er+=1
Winner =
evaluate(board)ifwinner
!=0:
Breakr
eturn(winner)

#drivercode
Print("winneris:"+str(play_game()))

Output:
[[000]
[000]
[000]]
Boardafter1move
[[000]
[000]
[100]]
Boardafter2move
[[000]
[020]
[100]]
Boardafter3move
[[010]
[020]
[100]]
Boardafter4move
[[010]
[220]
[100]]
Boardafter5move
[[110]
[220]
[100]]
Boardafter6move
[[110]
[220]
[120]]
Boardafter7move
[[110]
[220]
[121]]
Boardafter8move
[[110]
[222]
[121]]
Winneris:2
Experiment no. – 07
Objective: write a python program to remove stopwords for a given passage
from a textfile using nltk?

Import nltk
From nltk.corpus import stopwords
F1 = open("file1.txt","r")
F2 = open("file2.txt","w")
Stop = stopwords.words('english')
For line in f1:
W = line.split(" ")
For word in w
If word not in stop:
F2.write(word)
F2.write(" ")
F1.close()
F2.close()

Output:
Experiment no. – 08
Objective: write a python program to implement stemming for a given
sentence using nltk?

From nltk.stem import porterstemmer


From nltk.tokenize import word_tokenize
Ps= porterstemmer()
Example_words = [" python,pythonly,phythoner,pythonly"]
For w in example_words:
Print(ps.stem(w))

Output:
Python,pythonly,phythoner,pythonli
Experiment no. – 09
Objective: write a python program to pos(partsof speech) tagging for the
give sentence using nltk?

Import nltk
Text = nltk.word_tokenize('ive into nltk: part-of-speech tagging and pos tagger')
Pos = nltk.pos_tag(text)
Print(text)
Print(pos)

Output:
['ive', 'into', 'nltk', ':', 'part-of-speech', 'tagging', 'and', 'pos', 'tagger']
[('ive', 'jj'), ('into', 'in'), ('nltk', 'nnp'), (':', ':'), ('part-of-speech', 'jj'), ('tagging','nn'), ('and', 'cc'),
('pos', 'nnp'), ('tagger', 'nnp')]
Experiment no. – 10
Objective: write a python program to implement lemmatization using nltk?

# import these modules


from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print("rocks :", lemmatizer.lemmatize("rocks"))


print("corpora :", lemmatizer.lemmatize("corpora"))

# a denotes adjective in "pos"


print("better :", lemmatizer.lemmatize("better", pos ="a"))

Output:
rocks : rock
corpora : corpus
better : good
Experiment no. – 11

Objective: write a python program for text classification for the give
sentence using nltk.

Import nltk
Import random
From nltk.corpus import movie_reviews
Documents = [(list(movie_reviews.words(fileid)), category)
For category in movie_reviews.categories()
For fileid in movie_reviews.fileids(category)]
Random.shuffle(documents)
Print(documents[1])
All_words = []
For w in movie_reviews.words():
All_words.append(w.lower())
All_words = nltk.freqdist(all_words)
Print(all_words.most_common(15))
Print(all_words["stupid"])

Output:
([u'making', u'your', u'first', u'feature', u'film', u'ain', u"'", u't', u'easy', u'.', u'assemble',u'a',
u'decent', u',', u'if', u'not', u',', u'strong', u'cast', u',', u'as', u'writer', u'/', u'director',u'robert',
u'moresco', u'has', u'done', u'with', u'one', u'eyed', u'king', u',', u'and', u'you',u"'", u're',
u'already', u'ahead', u'of', u'the', u'game', u'.', u'but', u'rehash', u'old', u'plot',u'lines', u',',
u'tired', u'dialogue', u',', u'and', u'standard', u'clich', u'?', u's', u',', u'and',u'a', u'well', u'-',
u'intentioned', u'effort', u'such', u'as', u'this', u'one', u'could',u'jeopardize', u'your', u'chance',
u'at', u'a', u'second', u'feature', u'film', u'.', u'how',u'many', u'more', u'movies', u'do', u'we',
u'need', u'about', u'a', u'rough',u'neighborhood', u'full', u'of', u'lifelong', u'friends',
u'hopelessly', u'turned', u'to',u'crime', u'or', u'worse', u'?', u'the', u'enormous', u'catalog', u'of',
u'such', u'movies',u'might', u'dissuade', u'a', u'filmmaker', u'from', u'making', u'yet', u'another',
u',',u'but', u'here', u'we', u'have', u'it', u'.', u'again', u'.', u'five', u'irish', u'kids', u'in', u'nyc',u"'",
u's', u'hell', u"'", u's', u'kitchen', u'make', u'an', u'overemotional', u'pact', u'over',u'some',
u'stolen', u'rings', u'on', u'an', u'anonymous', , u'and', u'slow', u'motion', u'.',u'in', u'the', u'film',
u"'", u's', u'first', u'scene', u'.', , '], u'neg')

You might also like