You are on page 1of 17

THE TECHNOLOGICAL INTITUTE OF TEXTILE AND SCIENCE’S

BIRLA COLONY, BHIWANI – 127021

ARTIFICIAL INTELLIGENCE
LAB USING PYTHON

SUBMITTED TO SUBMITTED BY
NAME:- NITISH BANSAL
MR. ANIL YADAV ROLL NO:- 19CE076
UNV ROLL NO:-
INDEX
S.NO. EXPERIMENT DATE PAGE NO. TEACHER’S SIGN
EXPERIMENT - 1
AIM: - Introduction to Python

THEORY: -
Python is a Popular Programming Language. It was created by ‘Guido Van
Rossum’ in 1991 and was further developed by the Python Software Foundation. Its
Syntax allows programmers to express their concepts in fewer lines of code.
Python is a Programming Language that lets you work quickly and integrate
systems more efficiently. The two major Python Versions are: “PYTHON 2 & PYTHON
3”. Both are quite different.

 USES
Python Language is used for: -
 Web Development (Server-Side)
 Software Development
 Mathematic
 System Scripting

 ACTIONS PERFORMED BY PYTHON


 Python can be used on a Server to create Web Applications.
 Python can be used alongside Software to create Workflows.
 Python can connect to Database Systems. It can also Read and Modify Files.
 Python can be used to handle Big Data and perform Complex Mathematics.
 Python can be used for Rapid Prototyping, or for Production Ready
Software Development.

 ADVANTAGES
 Python works on different platforms (Windows, Mac, Linux and Raspberry
Pi).
 Python has a Simple Syntax similar to the English Language.
 Python has Syntax that allows Developers to write programs with fewer
lines than some Other Programming Languages.
 Python runs on an Interpreter System, meaning that Code can be executed
as soon as it is written. This means that Prototyping can be very quick.
 Features
 Interpreted
 There are no separate Compilation and Execution steps like C and
C++.
 Directly run the program from the Source Code.
 Internally, Python converts the Source Code into an Intermediate
form called Bytecodes which is then translated into Native Language
of specific Computer to run it.
 No need to worry about Linking and Loading with Libraries.
 Platform Independent
 Python Programs can be Developed and Executed on multiple
Operating System platforms.
 Python can be used on Linux, Windows, Macintosh, Solaris and many
more.
 Free and Open Source; Redistributable
 High-level Language
 In Python, no need to take care about Low-Level details such as
managing the Memory used by the Program.
 Simple
 Closer to English Language; Easy to Learn
 More Emphasis on the solution to the problem rather than the
Syntax.
 Embeddable
 Python can be used within C/C++ Program to give Scripting
capabilities for the Program’s Users.
 Robust:
 Exceptional Handling Features.
 Memory Management Techniques are inbuilt.
 Rich Library Support
 The Python Standard Library is vary Vast.
 Known as the “Batteries Included” Philosophy of Python ;It can help
do various things involving Regular Expressions, Documentation
Generation, Unit Testing, Threading, Databases, Web Browsers, CGI,
Email, XML, HTML, WAV Files, Cryptography, GUI and many more.
 Besides the Standard Library, there are various other High-Quality
Libraries such as the Python Imaging Library which is an amazingly
Simple Image Manipulation Library.
EXPERIMENT – 2
AIM: - WAP to Implement Water Jug Problem

THEORY: -
There are two Jugs of a litre and b litre. Neither has any measuring mark on it.
There is a pump that can be used to fill the Jugs with Water. The Goal is to get
exactly x litre of Water into any Jug. Assuming that We have unlimited supply of
Water.
The operations We can perform are:
1. Empty a Jug
2. Fill a Jug
3. Pour Water from one Jug to the other until one of the Jugs is either
empty or full

CODE: -
print("** WATER JUG PROBLEM **\n")
a=int(input("Enter Max Capacity Jug A: "))
b=int(input("Enter Max Capacity Jug B: "))
ai=0
bi=0
print("Initial State of Both Jugs:",(ai,bi),"\n")
af=int(input("Final State of Jug A: "))
bf=int(input("Final State of Jug B: "))
print("Final State of Both Jugs:",(af,bf),"\n")
print("List Of Operations You can Do:\n")
print("1.Fill Jug A Completely")
print("2.Fill Jug B Completely")
print("3.Empty Jug A Completely")
print("4.Empty Jug B Completely")
print("5.Pour From Jug A till Jug B filled Completely or A becomes empty")
print("6.Pour From Jug B till Jug A filled Completely or B becomes empty")
print("7.Pour all From Jug B to Jug A")
print("8.Pour all From Jug A to Jug B\n")
while ((ai!=af or bi!=bf)):
op=int(input("Enter the Operation: "))
if(op==1):
ai=a
elif(op==2):
bi=b
elif(op==3):
ai=0
elif(op==4):
bi=0
elif(op==5):
if(b-bi>ai):
bi=ai+bi
ai=0
else:
ai=ai-(b-bi)
bi=b
elif(op==6):
if(a-ai>bi):
ai=ai+bi
bi=0
else:
bi=bi-(a-ai)
ai=a
elif(op==7):
ai=ai+bi
bi=0
elif(op==8):
bi=bi+ai
ai=0
print(ai,bi)
print("!! Reached the Goal State !!")
OUTPUT
EXPERIMENT – 3
AIM: - WAP to Implement Breadth-First Search

CODE: -
graph = {
'A' : ['B','C'],
'B' : ['A', 'D'],
'C' : [],
'D' : ['A']
}
def bfs(graph, node):
visited = []
queue = [node]
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
return visited
print ("** BREADTH FIRST SEARCH **\n")
print("The Nodes of the Graph Visited using BFS, starting from 'A':")
bfs(graph, 'A')
OUTPUT
EXPERIMENT – 4
AIM: - WAP to Implement Depth-First Search

CODE: -
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F', 'G'],
'D' : ['H'],
'E' : ['I'],
'F' : ['J'],
'G' : ['K'],
'H' : [],
'I' : [],
'J' : [],
'K' : []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print ("** DEPTH FIRST SEARCH **\n")
print("The Nodes of the Graph Visited using DFS, starting from 'A':\n ")
dfs(visited, graph, 'A')
OUTPUT
EXPERIMENT – 5
AIM: - WAP to Implement 8-Puzzle Problem

CODE: -
EXPERIMENT – 6
AIM: - WAP to Implement Tic Tac Toe Game

THEORY: -
The Tic Tac Toe Game is played on a 3x3 grid. The Game is played between two
Players. The Player who formed Horizontal, Vertical, or Diagonal sequence of same
three marks Wins.
In the Tic Tac Toe Computer Program, the Game is played between the Player
and Computer. The Player chooses if he/she wants to be X or O. Who takes the first
turn is randomly chosen. Then the Player and Computer take turns making moves.
After the Player or Computer makes a move, the program checks whether the Player
has Won, Loss or caused a Tie. After the game is over, the program asks the Player if
he/she wants to play again.

CODE: -
import random
def drawBoard(board):
print(' '+ board[1] +' | '+ board[2] +' | '+ board[3])
print('---|---|---')
print(' '+ board[4] +' | '+ board[5] +' | '+ board[6])
print('---|---|---')
print(' '+ board[7] +' | '+ board[8] +' | '+ board[9])
def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
if random.randint(0, 1) == 0:
return 'Computer'
else:
return 'Player'
def playAgain():
print('Do you want to Play Again?(y/n)')
return input().lower().startswith('y')
def makeMove(board, letter, move):
board[move] = letter
def isWinner(bo, le):
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def getBoardCopy(board):
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def isSpaceFree(board, move):
return board[move] == ' '
def getPlayerMove(board):
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,
int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getComputerMove(board, computerLetter):
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move
if isSpaceFree(board, 5):
return 5
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
def isBoardFull(board):
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True

# Driver Code
print('** TIC TAC TOE **\n')
while True:
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('\nThe ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'Player':
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('\nHooray! You have Won the Game\n')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('\nThe Game is a Tie\n')
break
else:
turn = 'Computer'
else:
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('\nThe Computer has Beaten you! You Lose\n')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('\nThe game is a tie!')
break
else:
turn = 'Player'
if not playAgain():
break
OUTPUT

You might also like