Artificial Intelligence Lab Manual: ACADEMIC YEAR: 2019-2020 Second Semester
Artificial Intelligence Lab Manual: ACADEMIC YEAR: 2019-2020 Second Semester
Artificial Intelligence Lab Manual: ACADEMIC YEAR: 2019-2020 Second Semester
LAB MANUAL
SECOND SEMESTER
LIST OF PROGRAMS
PROGRAM TITLE OF THE PROGRAM PAGE
NO NUMBER
1. ( a ) Write a python program to print the multiplication table for the given 4
number.
(b) Write a python program to check whether the given number is prime or 4
not.
(c) Write a python program to find factorial of the given number. 5
2. Write a python program to implement simple Chatbot. 6
AI WITH PYTHON
Since the invention of computers or machines, their capability to perform various tasks has experienced
an exponential growth. Humans have developed the power of computer systems in terms of their diverse
working domains, their increasing speed, and reducing size with respect to time.
A branch of Computer Science named Artificial Intelligence pursues creating the computers or machines
as intelligent as human beings.
According to the father of Artificial Intelligence, John McCarthy, it is “The science and engineering of
making intelligent machines, especially intelligent computer programs”.
Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a software think
intelligently, in the similar manner the intelligent humans think. AI is accomplished by studying how
human brain thinks and how humans learn, decide, and work while trying to solve a problem, and then
using the outcomes of this study as a basis of developing intelligent software and systems.
While exploiting the power of the computer systems, the curiosity of human, lead him to wonder, “Can a
machine think and behave like humans do?”
Thus, the development of AI started with the intention of creating similar intelligence in machines that
we find and regard high in humans.
Artificial intelligence is considered to be the trending technology of the future. Already there are a number
of applications made on it. Due to this, many companies and researchers are taking interest in it. But the
main question that arises here is that in which programming language can these AI applications be
developed? There are various programming languages like Lisp, Prolog, C++, Java and Python, which
can be used for developing applications of AI. Among them, Python programming language gains a huge
popularity and the reasons are as follows:
Python involves very less coding and simple syntax among other programming languages which can be
used for developing AI applications. Due to this feature, the testing can be easier and we can focus more
on programming.
A major advantage for using Python for AI is that it comes with inbuilt libraries. Python has libraries for
almost all kinds of AI projects. For example, NumPy, SciPy, matplotlib, nltk, SimpleAI are some the
FEATURES OF PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed
to be highly readable. It uses English keywords frequently where as other languages use punctuation, and
it has fewer syntactical constructions than other languages. Python's features include the following −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and crossplatform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
Extendable − We can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell scripting.
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 Emil
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
# To ask month and year from the user# Python program to display calendar of given
month of the year
# import module
import calendar
Output:
Enter month: 10
October 2019
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 31
# 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
Code:
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j], )
# attacking queens
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
return True
board[i][col] = 0
return False
# feasible solutions.
def solveNQ():
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
if solveNQUtil(board, 0) == False:
return False
printSolution(board)
return True
solveNQ()
Output:
runfile('C:/Users/Rajan/NQueen.py', wdir='C:/Users/Rajan')
0010
1000
0001
0100
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)
Course Code: COMP 241 19
AI Lab Manual
explored.append(node)
neighbours = graph[node]
# add neighbours of node to queue
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)
'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']
7. Consider this graph, and implement the code in python for Depth first Search Traversal.
# Driver Code
dfs(visited, graph, 'A')
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:
9. (a) Write a python program to remove punctuations from the given string?
Code:
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
no_punct = ""
print(no_punct)
Output:
#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 =[]
if isWordGuessed(secretWord, lettersGuessed):
user_input = str(user_input)
user_input = user_input.lower()
lettersGuessed.append(user_input)
if user_input in secretWord:
else:
guessesLeft -= 1
else:
return print("Sorry, you ran out of guesses. The word was " + str(secretWord))
hangman('apple')
Output:
-----------
Good guess: a_ _ _ _
-----------
-----------
-----------
-----------
-----------
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')