AI File
AI File
Management
Artificial Intelligence
Lab File
Submitted to: Submitted by:
INDEX
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:
print("The factorial of",num,"is",recur_factorial(num))
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
# 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:
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']]
PROGRAM - 4
4 (a). Write a python program to Illustrate Different Set Operations?
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
12
34 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
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))
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
21 + 22 = 43
PROGRAM-5
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]]
# iterate through rows
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 resul
PROGRAM-6
6.Write a python program to implement Breadth first search Traversal?
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]
# 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)
# return path if neighbour is goal
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
OUTPUT: -
HERE'S THE SHORTEST PATH BETWEEN NODES 'D' AND 'F': ['D', 'B', 'A', 'C', 'F']
PROGRAM-7
7. Write a python program to implement Water Jug Problem?
A Water Jug Problem: You are given two jugs, a 4-gallon one and a 3-gallon one, a
pump which has unlimited water which you can use to fill the jug, and the ground on
which water may be poured. Neither jug has any measuring markings on it. How can
you get exactly 2 gallons of water in the 4-gallon jug?
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:
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
no_punct = ""
print(no_punct)
Output:
#print(words)
words.sort()
print(word)
Output:
Example
Hello
Is
With
an
cased
letters
this
PROGRAM-9
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)
def chooseRandomMoveFromList(board, movesList):
# 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.
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()
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
| |
AI Lab Manual
Course Code:
15CS3111
4
| |
O| |
| |
| |
X|X|O
| |
| |
O| |X
| |
| |
O|X|
| |
| |
X|X|O
| |
| |
O|O|X
| |
AI Lab Manual
Course Code:
15CS3111
WHAT IS YOUR NEXT MOVE? (1-9)
| |
O|X|X
| |
| |
X|X|O
| |
| |
O|O|X
| |
AI Lab Manual