Artificial Intelligence Lab Manual: (ACADEMIC YEAR: 2018-19) Semester - I
Artificial Intelligence Lab Manual: (ACADEMIC YEAR: 2018-19) Semester - I
ARTIFICIAL INTELLIGENCE
LAB MANUAL
[ACADEMIC YEAR: 2018-19]
SEMESTER - I
List of Experiments
1. (a). Write a python program to print the multiplication table for the given number?
(b). Write a python program to check whether the given number is prime or not?
(c) Write a python program to find factorial of the given number?
3. (a) Write a python program to implement List operations (Nested List, Length,
Concatenation, Membership, Iteration, Indexing and Slicing)?
(b) Write a python program to implement List methods (Add, Append, Extend & Delete).
1. (a). Write a python program to print the multiplication table for the given
number?
Code:
# Python program to find the multiplication table (from 1 to 10) of a number
input by the user
for i in range(1,11):
print(num,'x',i,'=',num*i)
Output:
(b). Write a python program to check whether the given number is prime or not?
Code:
#num = 407
for i in range(2,num):
rem=num%i
if rem == 0:
break
if rem == 0:
print(num,"is not a prime number")
else:
print(num,"is a prime number")
Enter a number: 5
5 is a prime number
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
#num = 5
if num < 0:
elif num == 0:
else:
Output:
Enter a number: 5
Code:
print("=====================================")
print("Hi")
print("Quit")
while True:
question = question.lower()
if question in ['hi']:
print("Hello")
print("I am fine")
break
else:
Output:
==============================
Hi
Quit
Hello
I am fine
My name is Emilia
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
print("Length",my_list,":",len(my_list))
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
#my_list[4.2]
# Nested List
# Nested indexing
# Output: 3
print(n_list[0][1])
# Output: 8
print(n_list[1][3])
# Nested List2
# Nested indexing
# Output: a
print(n_list2[0][1])
# Output: 5
print(n_list2[1][3])
concat1=[1,3,5]
concat2=[7,8,9]
print("Concatenation:",concat1,concat2,":",concat1+concat2)
repetion_string="Hello"
print("Repetition:",repetion_string,repetion_string * 4)
Output:
(b) Write a python program to implement list operations (add, append, extend &
delete)
Code:
myList = ["Earth", "revolves", "around", "Sun"]
print(myList)
print(len(myList))
print(myList[0])
print(myList[3])
print(myList[1:3])
print(myList[-1])
#print(myList[4])
myList.insert(0,"The")
print(myList)
print(len(myList))
myList.insert(4,"the")
print(myList)
myList.append("continuously")
print(myList)
print(len(myList))
myList.extend(["for", "sure"])
print(myList)
print(len(myList))
myList.append(["The","earth","rotates"])
print(myList)
print(len(myList))
myList.remove("The")
myList.remove(myList[3])
print(myList)
Output
Earth
Sun
['revolves', 'around']
Sun
['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously', 'for', 'sure', ['The',
'earth', 'rotates']]
10
['Earth', 'revolves', 'around', 'Sun', 'continuously', 'for', 'sure', ['The', 'earth', 'rotates']]
Code:
# Program to perform different set operations like in mathematics
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
# set intersection
# set difference
Output:
(b). Write a python program to generate Calendar for the given month and
year?
Code:
# Python program to display calendar of given month of the year
# import module
import calendar
yy = 2014
mm = 11
# To ask month and year from the user# Python program to display calendar of given
month of the year
# import module
import calendar
yy = 2014
mm = 11
Output:
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
# Program make a simple calculator that can add, subtract, multiply and divide
using functions
# define functions
return x + y
return x - y
return x * y
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
print(num1,"-",num2,"=", subtract(num1,num2))
print(num1,"*",num2,"=", multiply(num1,num2))
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):1
21 + 22 = 43
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
Z = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
for r in Z:
print(r)
Output:
[17, 15, 4]
[10, 12, 9]
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
Output:
[12, 4, 3]
[7, 5, 8]
Code:
"""
traversing a graph, and for getting the shortest path between 2 nodes
of a graph.
"""
explored = []
queue = [start]
while queue:
node = queue.pop(0)
explored.append(node)
neighbours = graph[node]
queue.append(neighbour)
return explored
explored = []
queue = [[start]]
if start == goal:
while queue:
path = queue.pop(0)
node = path[-1]
neighbours = graph[node]
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
if neighbour == goal:
return new_path
explored.append(node)
if __name__ == '__main__':
'B': ['A','D'],
'C': ['A','E','F'],
'D': ['B'],
'E': ['C',],
'F': ['C'],
# A
# /\
# / \
# B C
# / /\
# / / \
# D E F
bfs_connected_component(graph, 'A'))
OUTPUT: -
HERE'S THE SHORTEST PATH BETWEEN NODES 'D' AND 'F': ['D', 'B', 'A', 'C', 'F']
Write a program in python to define a set of operators (Rules) that will take us from
one state to another:
Code:
if rno==1:
if x<4:x=4
if rno==2:
if y<3:y=3
if rno==5:
if x>0:x=0
if rno==6:
if y>0:y=0
if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)
if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3
if rno==9:
if x+y<=4 and y>0:x,y=x+y,0
if rno==10:
if x+y<=3 and x>0:x,y=0,x+y
Output:
8. (a) Write a python program to remove punctuations from the given string?
Code:
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
no_punct = ""
print(no_punct)
Output:
words = my_str.split()
#print(words)
words.sort()
print(word)
Output:
Example
Hello
Is
With
an
cased
letters
this
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.
Python Code:
def getAvailableLetters(lettersGuessed):
'''
returns: string, comprised of letters that represents what letters have not
'''
import string
fullstring = string.ascii_lowercase
lettersLeft = ''
return lettersLeft
'''
'''
wordGuessed = ''
if letter in lettersGuessed:
else:
return wordGuessed
'''
False otherwise
'''
numCorrect = 0
if letter in lettersGuessed:
numCorrect += 1
else:
return False
return True
def hangman(secretWord):
guessesLeft = 8
lettersGuessed =[]
print('-----------')
if isWordGuessed(secretWord, lettersGuessed):
user_input = str(user_input)
user_input = user_input.lower()
lettersGuessed.append(user_input)
if user_input in secretWord:
print('-----------')
else:
print('-----------')
guessesLeft -= 1
else:
print('-----------')
return print("Sorry, you ran out of guesses. The word was " + str(secretWord))
hangman('apple')
Output:
-----------
Good guess: a_ _ _ _
-----------
-----------
-----------
-----------
-----------
In the Tic Tac Toe computer program the player chooses if they want to be X or O. Who
takes the first turn is randomly chosen. Then the player and computer take turns making
moves. The boxes on the left side of the flow chart are what happens during the player’s turn.
The right side shows what happens on the computer's turn. After the player or computer
makes a move, the program checks if they won or caused a tie, and then the game switches
turns. After the game is over, the program asks the player if they want to play again.
Python Code:
import random
def drawBoard(board):
print(' | |')
print(' | |')
print('-----------')
print(' | |')
print(' | |')
print('-----------')
print(' | |')
print(' | |')
def inputPlayerLetter():
# Returns a list with the player's letter as the first item, and the computer's letter as the
second.
letter = ''
letter = input().upper()
# the first element in the tuple is the player's letter, the second is the computer's letter.
if letter == 'X':
else:
def whoGoesFirst():
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
return input().lower().startswith('y')
board[move] = letter
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
def getBoardCopy(board):
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def getPlayerMove(board):
move = input()
return int(move)
# Returns a valid move from the passed list on the passed board.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
# Given a board and the computer's letter, determine where to move and return that move.
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i
# Check if the player could win on his next move, and block them.
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
if move != None:
return move
if isSpaceFree(board, 5):
return 5
def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return False.
if isSpaceFree(board, i):
return False
return True
while True:
turn = whoGoesFirst()
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
break
else:
turn = 'computer'
else:
# Computer's turn.
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
break
else:
turn = 'player'
if not playAgain():
break
OUTPUT: -
DO YOU WANT TO BE X OR O?
| |
| |
| |
-----------
| |
| |
| |
-----------
| |
| |
| |
| |
| |
| |
-----------
| |
|X |
| |
-----------
| |
O| |
| |
| |
O| |
| |
-----------
| |
|X |
| |
-----------
| |
O| | X
| |
| |
O| |
| |
-----------
| |
X|X |O
| |
-----------
| |
O| |X
| |
| |
O|X|
| |
-----------
| |
X|X|O
| |
-----------
| |
O|O|X
| |
| |
O|X|X
| |
-----------
| |
X|X|O
| |
-----------
| |
O|O|X
| |
11.(a) Write a python program to remove stop words for a given passage from a text file
using NLTK?
Code:
import nltk
f1 = open("file1.txt","r")
f2 = open("file2.txt","w")
stop = stopwords.words('english')
w = line.split(" ")
for word in w:
f2.write(word)
f2.write(" ")
f1.close()
f2.close()
Output:
(b) Write a python program to implement stemming for a given sentence using
NLTK?
Code:
from nltk.stem import PorterStemmer
ps= PorterStemmer()
for w in example_words:
print(ps.stem(w))
Output:
python,pythonly,phythoner,pythonli
(c) Write a python program to POS (Parts of Speech) tagging for the give sentence
using NLTK?
Code:
import nltk
pos = nltk.pos_tag(text)
print(text)
print(pos)
Output:
[('ive', 'JJ'), ('into', 'IN'), ('NLTK', 'NNP'), (':', ':'), ('Part-of-speech', 'JJ'), ('tagging',
'NN'), ('and', 'CC'), ('POS', 'NNP'), ('Tagger', 'NNP')]
Code:
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize("cats"))
print(lemmatizer.lemmatize("cacti"))
print(lemmatizer.lemmatize("geese"))
print(lemmatizer.lemmatize("rocks"))
print(lemmatizer.lemmatize("pyth"))
print(lemmatizer.lemmatize("cats"))
Output:
cat
cactus
goose
rock
pyth
cat
(b) Write a python program to for Text Classification for the give sentence using
NLTK?
Code:
import nltk
import random
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')