AI Pratical File (Indervir Singh)
AI Pratical File (Indervir Singh)
Pratical File
2|Page
Task 1 Date:- 28-02-2023
Introduction to python
• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, Smalltalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Applications
1
Features in python
1. Free and Open Source : Python language is freely available at the official website and you
can download it from the given download link below click on the Download Python keyword.
2. Easy to code: Python is very easy to learn the language as compared to other languages like
C, C#, Javascript, Java, etc. It is very easy to code in the Python language and anybody can learn
Python basics in a few hours or days.
3. Easy to Read: As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the indentations rather
than by semicolons or brackets.
4. Object-Oriented Language: One of the key features of Python is Object-Oriented
programming. Python supports object-oriented language and concepts of classes, object
encapsulation, etc.
5. GUI Programming Support: Graphical User interfaces can be made using a module such as
PyQt5, PyQt4, wxPython, or Tk in python. PyQt5 is the most popular option for creating
graphical apps with Python.
6. High-Level Language: Python is a high-level language. When we write programs in Python,
we do not need to remember the system architecture, nor do we need to manage the memory.
7. Extensible feature: Python is an Extensible language. We can write some Python code into C
or C++ language and also we can compile that code in C/C++ language.
8. Easy to Debug: You will be able to quickly identify and correct the majority of your
program’s issues once you understand how to interpret Python’s error traces.
9. Python is a Portable language: Python language is also a portable language. For example, if
we have Python code for windows and if we want to run this code on other platforms such as
Linux, Unix, and Mac then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language: Python is also an Integrated language because we can
easily integrate Python with other languages like C, C++, etc.
11. Dynamically Typed Language: Python is a dynamically-typed language. That means the
type (for example- int, double, long, etc.) for a variable is decided at run time not in advance
because of this feature we don’t need to specify the type of variable.
2
Task 2 Date:- 7-03-2023
1. Arithmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations.
OUTPUT:
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
OUTPUT:
3
3. Logical operators: Logical operators are used to combine conditional statements:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
OUTPUT:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
OUTPUT:
5. Identity operators: Identity operators are used to compare the objects, not if they are equal,
but if they are actually the same object, with the same memory location:
a = 10
b = 20
4
c=a
print(a is not b)
print(a is c)
OUTPUT:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
OUTPUT:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
OUTPUT:
5
Task 3 Date:- 21-03-2023
OUTPUT:-
6
Task 4 Date:- 21-03-2023
OUTPUT:-
7
Task 5 Date:- 28-03-2023
8
parents[m] = n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
open_list.remove(n)
closed_list.add(n)
print('Path does not exist!')
return None
adjacency_list = {
'A': [('B', 1), ('C', 3), ('D', 7)],
'B': [('D', 5)],
'C': [('D', 12)]
}
graph1 = Graph(adjacency_list)
graph1.a_star_algorithm('A', 'D')
OUTPUT:-
9
Task 6 Date:- 28-03-2023
10
if self.board[i][n - 1 - i] != player:
win = False
break
if win:
return win
return False
for row in self.board:
for item in row:
if item == '-':
return False
return True
def is_board_filled(self):
for row in self.board:
for item in row:
if item == '-':
return False
return True
def swap_player_turn(self, player):
return 'X' if player == 'O' else 'O'
def show_board(self):
for row in self.board:
for item in row:
print(item, end=" ")
print()
def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
while True:
print(f"Player {player} turn")
self.show_board()
row, col = list(
map(int, input("Enter row and column numbers to fix spot: ").split()))
print()
self.fix_spot(row - 1, col - 1, player)
if self.is_player_win(player):
print(f"Player {player} wins the game!")
break
if self.is_board_filled():
print("Match Draw!")
break
player = self.swap_player_turn(player)
print()
self.show_board()
tic_tac_toe = TicTacToe()
tic_tac_toe.start()
11
OUTPUT:-
12
Task 7 Date:- 4-04-2023
Given dataset:
se restec
age x cp trestbps chol fbs g thalach exang oldpeak slope ca thal Heartdisease
13
OUTPUT:-
14
Task 8 Date:- 11-04-2023
OUTPUT:-
15
Task 9 Date:- 25-04-2023
16
def west(self, cell): row = cell.row; col = cell.col
if col > 0: col -= 1 return
self._next_cell_if_not_blocked(cell, row, col)
def east(self, cell): row = cell.row; col = cell.col
if col < world_bounds_cols-1: col += 1
return self._next_cell_if_not_blocked(cell, row, col)
def _next_cell_if_not_blocked(self, cell, row, col):
n = self.cells[row][col]
if n.blocks: return
cell
return n
def str (self): return
pformat(self.as_array())
def repr (self): return
self. str ()
class ValueIterationAlgo(object): def
__init__ (self, discount_factor, world): self.discount_factor = discount_factor
self.world = world
def update(self, state):
if state.is_terminal or state.blocks: return
max_pv = 0
= [0.8*self.world.north(state).value + 0.1*self.world.west(state).value +
0.1*self.world.east(state).value, 0.8*self.world.south(state).value +
0.1*self.world.west(state).value +
0.1*self.world.east(state).value,
0.8*self.world.east(state).value + 0.1*self.world.north(state).value +
0.1*self.world.south(state).value,
0.8*self.world.west(state).value + 0.1*self.world.north(state).value +
0.1*self.world.south(state).value]
moves_directions = ['north', 'south', 'east', 'west'] max_idx = np.argmax(moves_pvs)
max_pv = moves_pvs[max_idx] policy= moves_directions[max_idx]
state.value = self.discount_factor * max_pv + state.reward state.policy = policy
def str (self): return
pformat(self. dict )
def repr (self):
return self.
str ()
def done(): global world, prev_world
diff = np.abs(world.as_array() - prev_world) except RuntimeWarning:
pass return not (diff > epsilon).any()
epsilon = 0.0001 discount_factor = 0.9
def part_b(): global world, prev_world
world =
GridWorld(world_input) prev_world = np.ones_like(world_input)
print 'iteration {}'.format(iter_cnt).center(72, '-')
pprint(prev_world)
17
if done(): break
prev_world = world.as_array()
pprint(prev_world)
for cell in world: algo.update(cell) iter_cnt += 1
world_arr = world.as_array()
pprint(world_arr)
pprint(np.round(world_arr))
pprint(world.policy())
def part_c():
global world, prev_world discount_factor = 0.9
while(True):
world = GridWorld(world_input)
prev_world = np.ones_like(world_input)
print 'iteration {}, discount={}'.format( iter_cnt, discount_factor).center(72, '-')
pprint(prev_world)
if done(): break
prev_world = world.as_array()
pprint(prev_world)
for cell in world:
algo.update(cell)
iter_cnt += 1
world_arr = world.as_array()
pprint(world_arr)
pprint(np.round(world_arr))
pprint(world.policy())
if world.cells[2][3].policy != 'west': break discount_factor - = 0.01
print 'part b:' part_b()
print 'part c:' part_c()
OUTPUT:-
18
Task 10 Date:- 25-04-2023
19
value = 10 + Y*grid[4][1]
elif i==0 and j==3:
value = 5 + Y*grid[2][3]
else:
for direc in all_dirs:
if direc != None:
value += .25 * (0 + Y*direc)
else: value += .25 * (-1 + Y*grid[i][j])
grid[i][j] = value np.round(grid, 1)
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "RL_gridworld.ipynb", "provenance": [], "collapsed_sections": []
},
"kernelspec": { "name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown", "metadata": {
"id": "myRaAcABGHFC", "colab_type": "text"
},
"source": [
"# GridWorld State Value for all states"
]
},
{
"cell_type": "code", "metadata": {
"id": "SFh0zR4Bob25", "colab_type": "code", "colab": {
"base_uri": "https://localhost:8080/", "height": 104
}
"outputId": "24789b8a-3715-46c7-bb0f-cf5222fb5fdf"
},
"source": [
"import numpy as np\n", "\n",
"grid = np.zeros((5,5))\n", "grid"
],
"execution_count": 1, "outputs": [
{
"output_type": "execute_result", "data": {
"text/plain": [
"array([[0., 0., 0., 0., 0.],\n",
20
" [0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0.]])"
]
},
"metadata": {
"tags": []
},
"execution_count": 1
}
]
},
{
"cell_type": "code", "metadata": {
"id": "6T1uH2KYHBTY",
"colab_type": "code", "colab": {}
},
"source": [
"Y = .90 #discount value\n",
"for num in range(10): #number of times we will go through the whole grid\n", " for i in
range(5): #all the rows\n",
" for j in range(5): #all the columns\n", " \n",
" up_grid = grid[i-1][j] if i > 0 else 0\n",
" down_grid = grid[i+1][j] if i < 4 else 0 \n",
" left_grid = grid[i][j-1] if j > 0 else 0 \n",
" right_grid = grid[i][j+1] if j < 4 else 0 \n",
" all_dirs = [up_grid, down_grid, left_grid, right_grid] \n", "\n", " value=0 \n",
" if i==0 and j==1: # the position of A\n", " value = 10 + Y*grid[4][1]\n",
" elif i==0 and j==3: # the position of B\n", " value = 5 + Y*grid[2][3]\n",
" else:\n",
" for direc in all_dirs:\n", " if direc != 0: \n",
" value += .25 * (0 + Y*direc) #if we don't go out of the grid\n", " else:\n",
" value += .25 * (-1 + Y*grid[i][j]) #if we go out of the grid\n", "
\n",
21
}
},
"source": [ "np.round(grid, 1)"
],
"execution_count": 3, "outputs": [
{
"output_type": "execute_result", "data": {
"text/plain": [
"array([[ 3.3, 8.8, 4.4, 5.3, 1.5],\n",
" [ 1.5, 3. , 2.2, 1.9, 0.5],\n",
" [ 0. , 0.7, 0.7, 0.4, -0.4],\n",
" [-1. , -0.4, -0.3, -0.6, -1.2],\n",
" [-1.9, -1.3, -1.2, -1.4, -1.9]])"
]
},
"metadata": {
"tags": []
},
"execution_count": 3
}
]
},
{
"cell_type": "code", "metadata": {
"id": "DQZUbYefdPr1", "colab_type": "code", "colab": {}
},
"source": [ ""
],
"execution_count": 0, "outputs": []
]
OUTPUT:-
22