INDEX
Expt No List of Programs PageNos.
1 a) Write a program to print the multiplication table for the given number
b) Write a program to find factorial of a number
c) Write a program to check whether the given number is prime or not
a) Write program to implement Simple Calculator program
2 b) Write a program to generate Calendar for the given month and year
c) Write a program to Illustrate Different Set Operations
3 Write a program to implement simple Chat bot
a) Write a program to remove punctuations from the given string
4 b) Write a program to sort the sentence in alphabetical order
Write a program to Implement of Towers of Hanoi Problem.
5
Write a Program to Implement Breadth First Search.
6
7 Write a Program to Implement Depth First Search.
Write a program to implement Hill Climbing Algorithm
8
Write a program to implement A* Algorithm.
9
10 Write a program to implement Tic-Tac-Toe game.
Write a program to implement Water Jug Problem
11
Artificial Intelligence Manual
PROGRAM-1(A)
1A) Aim: Write a program to print the multiplication table for the given number
Program:
# Python program to find the multiplication table (from 1 to 10) of a number input by the
user
# Get input from the user
num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
Output:
Display multiplication table of?
55x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
PROGRAM-1(B)
1B) Aim: Write a program to find factorial of the given number
Program:
def recur_factorial(n):
if n == 1:
return n else:
return n*recur_factorial(n-1)
Artificial Intelligence Manual
num = int(input("Enter a number: ")) # check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers") elif num == 0:
print("The factorial of 0 is 1") else:
print("The factorial of",num,"is",recur_factorial(num))
Output:
Enter a number: 5
The factorial of 5 is 120
PROGRAM-1(C)
1C) Aim: Write a program to check whether the given number is prime or not?
Program:
# Python program to check if the input number is prime or not
num = int(input("Enter a number: "))
# prime numbers are greater than 1 if num > 1:
rem=1
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")
else:
print(num,"is not a prime number")
Output:
Enter a number: 5
5 is a prime number
Artificial Intelligence Manual
PROGRAM-2(A)
2A) Write a program to implement Simple Calculator program
Program:
# Program make a simple calculator that can add, subtract, multiply and divide using
functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the
user print("Select
operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
Artificial Intelligence Manual
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
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
Enter first number: 21
Enter second number: 22
21 + 22 = 43
PROGRAM-2(B)
2B) Aim: Write a program to generate Calendar for the given month and year
Program:
# Python program to display calendar of given month of the year # import
module
import calendar
yy = 2014
mm = 11
Artificial Intelligence Manual
# 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
# To ask month and year from the
user # yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar print(calendar.month(yy, mm))
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-2(C)
2C) Aim: Write a program to Illustrate Different Set Operations?
Program:
# Program to perform different set operations like in
mathematics # define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
Artificial Intelligence Manual
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output:
Union of E and N is {0, 1, 2, 3, 4, 5, 6,
8} Intersection of E and N is {2, 4}
Difference of E and N is {0, 8, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
Artificial Intelligence Manual
PROGRAM-3
Aim:
Write a program to implement simple Chat bot
Program:
print("Simple Question and Answering Program")
print("=====================================")
print(" You may ask any one of these questions")
print("Hi")
print("How are you?")
print("Are you working?")
print("What is your name?")
print("what did you do
yesterday?") print("Quit")
while True:
question = input("Enter one question from above list:")
question = question.lower()
if question in ['hi']:
print("Hello")
elif question in ['how are you?','how do you do?']:
print("I am fine")
elif question in ['are you working?','are you doing any job?']:
print("yes. I'am working in MRCET")
elif question in ['what is your name?']:
print("My name is Emilia")
name=input("Enter your name?")
print("Nice name and Nice meeting you",name)
elif question in ['what did you do yesterday?']:
print("I saw Bahubali 5 times")
Artificial Intelligence Manual
elif question in ['quit']:
break
else:
print("I don't understand what you said")
Output:
Simple Question and Answering Program
==============================
You may ask any one of these
questions Hi
How are you?
Are you
working?
What is your name?
what did you do
yesterday? Quit
Enter one question from above list:hi
Hello
Enter one question from above list:how are
you? I am fine
Enter one question from above list:are you working?
yes. I'am working in MRCET
Enter one question from above list:what is your name?
My name is Emilia
Enter your name?sachin
Nice name and Nice meeting you sachin
Enter one question from above list:quit
Artificial Intelligence Manual
PROGRAM-4(A)
Aim: Write a program to remove punctuations from the given string
Program:
# 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 string
no_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
PROGRAM-4(B)
Aim: 4(B).Write a program to sort the sentence in alphabetical order
Program:
# 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
Artificial Intelligence Manual
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
#print(words)
# sort the list
words.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
letter
s this
Artificial Intelligence Manual
PROGRAM-5
Aim: Write a Program to Implement of Towers of Hanoi Problem.
Program:
# Recursive Python function to solve tower of hanoi
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 0:
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk",n,"from rod",from_rod,"to rod",to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
# Driver code
n=4
TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Artificial Intelligence Manual
PROGRAM-6
Aim:
Write a Program to Implement Breadth First Search.
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited
nodes. queue = [] #Initialize a
queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each
node m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First
Search") bfs(visited, graph, '5') #
function calling
Output:
Following is the Breadth-First Search
537248
Artificial Intelligence Manual
PROGRAM-7
Aim:
Write a Program to Implement Depth First Search.
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node):
#function for dfs if node not in
visited: print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Output:
Following is the Depth-First Search
5
3
2
4
Artificial Intelligence Manual
PROGRAM-8
Aim:
Write a program to implement Hill Climbing Algorithm
Program:
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def routeLength(tsp, solution):
routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
Artificial Intelligence Manual
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def getBestNeighbour(tsp, neighbours):
bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength =
currentRouteLength bestNeighbour =
neighbour
return bestNeighbour, bestRouteLength
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)
while bestNeighbourRouteLength < currentRouteLength:
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
Artificial Intelligence Manual
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)
return currentSolution, currentRouteLength
def main():
tsp = [
[0, 400, 500, 300],
[400, 0, 300, 500],
[500, 300, 0, 400],
[300, 500, 400, 0]
print(hillClimbing(tsp))
if name == " main ":
main()
Output:
([1, 0, 3, 2], 1400)
PROGRAM-9
Aim:
Write a program to implement A* Algorithm
Program:
from collections import deque
class Graph:
def init (self, adjac_lis):
self.adjac_lis = adjac_lis
def get_neighbors(self, v):
return self.adjac_lis[v]
# This is heuristic function which is having equal values for all nodes
def h(self, n):
H={
'A': 1,
'B': 1,
'C': 1,
'D': 1
}
return H[n]
def a_star_algorithm(self, start, stop):
# In this open_lst is a lisy of nodes which have been visited, but who's
# neighbours haven't all been always inspected, It starts off with the
start #node
# And closed_lst is a list of nodes which have been visited
# and who's neighbors have been always inspected
open_lst = set([start])
closed_lst = set([])
# poo has present distances from start to all other
Artificial Intelligence Manual
nodes # the default value is +infinity
poo = {}
poo[start] = 0
# par contains an adjac mapping of all nodes
par = {}
par[start] = start
while len(open_lst) > 0:
n = None
# it will find a node with the lowest value of f() -
for v in open_lst:
if n == None or poo[v] + self.h(v) < poo[n] + self.h(n): n
= v;
if n == None:
print('Path does not exist!')
return None
# if the current node is the stop
# then we start again from start if n == stop:
reconst_path = []
while par[n] != n:
reconst_path.append(n) n =
par[n]
reconst_path.append(start)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
# for all the neighbors of the current node do
for (m, weight) in self.get_neighbors(n):
# if the current node is not presentin both open_lst and
closed_lst
# add it to open_lst and note n as it's par
if m not in open_lst and m not in closed_lst:
open_lst.add(m)
par[m] = n
poo[m] = poo[n] + weight
# otherwise, check if it's quicker to first visit n, then m
Artificial Intelligence Manual
# and if it is, update par data and poo data
# and if the node was in the closed_lst, move it to open_lst
else:
if poo[m] > poo[n] + weight:
poo[m] = poo[n] + weight
par[m] = n
if m in closed_lst:
closed_lst.remove(m)
open_lst.add(m)
Artificial Intelligence Manual
# remove n from the open_lst, and add it to
closed_lst # because all of his neighbors were
inspected open_lst.remove(n)
closed_lst.add(n)
print('Path does not exist!')
return None
adjac_lis = {
'A': [('B', 1), ('C', 3), ('D', 7)],
'B': [('D', 5)],
'C': [('D', 12)]
}
graph1 = Graph(adjac_lis)
graph1.a_star_algorithm('A', 'D')
Output:
Path found: ['A', 'B', 'D']
Artificial Intelligence Manual
PROGRAM-10
Aim:
Write a program to implement Tic-Tac-Toe game.
Program:
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'
#This Function Draws Game Board
def DrawBoard():
print(" %c | %c | %c " %
(board[1],board[2],board[3])) print(" | |
")
print(" %c | %c | %c " %
(board[4],board[5],board[6])) print(" | |
")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print(" | | ")
#This Function Checks position is empty or not
def CheckPosition(x):
Artificial Intelligence Manual
if(board[x] == ' '):
return True
else:
return False
#This Function Checks player has won or not
def CheckWin():
global Game
#Horizontal winning condition
if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '):
Game = Win
elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '):
Game = Win
elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):
Game = Win
#Vertical Winning Condition
elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '):
Game = Win
elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '):
Game = Win
elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '):
Game=Win
#Diagonal Winning Condition
elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '):
Game = Win
elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '):
Game=Win
#Match Tie or Draw Condition
elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and board[5]!=' ' and
board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '):
Game=Draw
else:
Game=Running
print("Tic-Tac-Toe Game Designed By Sourabh Somani")
print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
time.sleep(3)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
print("Player 1's chance")
Artificial Intelligence Manual
Mark =
'X' else:
print("Player 2's chance")
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark :
"))
if(CheckPosition(choice)):
board[choice] = Mark
player+=1 CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
Output:
[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1
move [[0 0 0]
[0 1 0]
[0 0 0]]
Board after 2
move [[0 0 0]
[0 1 0]
[0 2 0]]
Board after 3
move [[0 0 0]
[0 1 0]
[1 2 0]]
Board after 4
move [[0 0 2]
[0 1 0]
[1 2 0]]
Board after 5
move [[0 0 2]
Artificial Intelligence Manual
[0 1 0]
[1 2 1]]
Board after 6
move [[0 0 2]
[0 1 2]
[1 2 1]]
Board after 7
move [[0 0 2]
[1 1 2]
[1 2 1]]
Board after 8
move [[2 0 2]
[1 1 2]
[1 2 1]]
Board after 9
move [[2 1 2]
[1 1 2]
[1 2 1]]
Winner is: -1
Artificial Intelligence Manual
# Initialize dictionary with # default value as false.
visited = defaultdict(lambda: False)
# Recursive function which prints the # intermediate steps to reach
the final # solution and return boolean value
# (True if solution is possible, otherwise False).
# amt1 and amt2 are the amount of water
present # in both jugs at a certain point of
time. def waterJugSolver(amt1, amt2):
# Checks for our goal
and # returns true if
achieved.
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
# Checks if we have already visited the
# combination or not. If not, then it proceeds further.
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
# Changes the boolean value of # the combination as it is visited.
visited[(amt1, amt2)] = True
# Check for all the 6 possibilities and
# see if a solution is found in any one of them.
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))))
# Return False if the combination is
# already visited to avoid repetition otherwise
# recursion will enter an infinite loop.
else:
return False
print("Steps: ")
Artificial Intelligence Manual
# Call the function and pass the
# initial amount of water present in both jugs.
waterJugSolver(0, 0)
Output:
Steps:
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2
True
Artificial Intelligence Manual