AI Practicals

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 108

TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no.

719

Practical No. 1
Django Framework
Aim: DJANGO

Installing Django with command prompt

Creating a project

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Change the directory

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Now, create an app

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Go In APPom1/Views.py And Create a Function Welcome And Learn Which Returns HTTP
Response And Render

Create html file

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Now, create urls.py In APPom1 And Add Path for Functions of View Folder.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Then, Go For urls.py Of Project Folder And Add Path For Whole kishanProject

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Run the project

Create an application named "register" in the same project that you were already working on.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Create An HTML File In register To Use register and submit Function .

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Code for register.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Restration Form</title>
</head>
<body>
<form action="submit">
<center>
<table >
<tr>
<td><i><h1>First Name:</h1></i></b></td>
<td><input type="text"name="1st name" maxlength="15" required="">
</td>
</tr>
<tr><td> <b><i><h1 style ="size:20">Last name:</h1></i></b></td>
<td><input type="text"name="last name" maxlength="15" required="">
</td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">Password</h1></i></b></td>
<td><input type="password"name="psw" required=""></td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">Gender:</h1></i></b></td>
<td><input type="radio" name="gender">Male
<input type="radio" name="gender">Female
</td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">Date Of Birth</h1></i></b></td>
<td><input type="date of birth" name="dob" required=""></td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">Phone no:</h1></i></b></td>
<td><input type="number" name="phone no" required=""></td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">E-mail:</h1></i></b></td>
<td><input type="email" name="mail" required=""></td>
</tr><br>
<tr><td><b><i><h1 style ="size:20">Address:</h1></i></b></td>
<td><input type="text" name="address" maxlength="50" required="" ></td>
</tr><br>
</table>
<input type="submit" name="Submit">
<input type="reset" name="Reset">
</center>
</form>
</body>
</html>

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Create submit.html and code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Success</title>
</head>
<body>
<h1>submit Successfully</h1>
</body
</html>

Go to register/views.py

from django.shortcuts import render


from django.http import HttpResponse
# Create your views here.
def register(request):
return render(request,'register.html')
def submit(request):
return render(request,'submit.html')

Go to register/urls .py

from django.urls import path


from .import views
urlpatterns = [
path('register/',views.register,name = 'register'),
path('register/submit/', views.submit, name='submit'),
]

Go to project KishanProject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('register.urls')),
]

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Go to settings.py Present In Project File And Add App Name Under INSTALLED_APPS

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'APPom1'
'register'
]

Now, Go on Terminal And Run The App.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

B. Explore the "Admin" application that Django provides.(Create "superuser", log into the
administration site and then explore.)

PS C:\Users\Kishan\PycharmProjects\DjangoProject\KishanProject> py manage.py
createsuperuser
Username (leave blank to use 'kishan'): Kishan
Email address: [email protected]
Password:
Password (again):
The password is too similar to the username.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Flask
Aim. FLASK FRAMEWORK

Code.

1.First Deactivate the virtual Environment


Command – deactivate
2.Creating the virtual env with command
Py -m venv virtualenvname
3.Give path reference to file
Virtualenvname/scripts/activate

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

pip install flask

Commands to run file

1.set FLASK_APP=KPR(name of file)  


2.set FLASK_ENV=development 
3.flask run

Go to kishanflask.py file and import flask create a home page


Source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<div class="topnav">
<a class="active" href="/subpage1">Home</a>
<a href="/about">ABOUT</a>
<a href="/todo">TODO LIST</a>
<a href="/profilepage/om">PROFILE PAGE</a>
</div>
<div style="padding-left:16px">

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

<h2>WELCOME TO HOME PAGE</h2>


<p>FLASK WEBPAGE</p>
</div>

</body>
</html>

Create a templates folder and inside it put all HTML pages.


Source code:
Welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="topnav">
<a class="active" href="/subpage1">Home</a>
<a href="/about">ABOUT</a>

<a href="/profilepage/om">PROFILE PAGE</a>


</div>
<div style="padding-left:16px">
<h2>WELCOME TO HOME PAGE</h2>
<p>FLASK WEBPAGE</p>
</div>
</body>
</html>

Go to kishanflask.py file and create a subpage1.


from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def welcome():
return render_template('welcome.html')
#if __name__ =="__main__":
# app.run(debug=True)
#2nd action
@app.route("/subpage1")
def myfirstpage():
return render_template('register.html')

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

register.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action = "about">
<div class="container">
<div class="card">
<h2 class="heading">Register</h2>
<p class="request">Please fill in this form to create an account.</p
>
<div class="input-box">
<label for="first-name"><b>First Name</b></label>
<input
type="text"
placeholder="First Name..."
name="first-name"
id="first-name"
required
/>
<label for="last-name"><b>Last Name</b></label>
<input
type="text"
placeholder="Last Name..."
name="last-name"
id="last-name"
required
/>
<label for="email"><b>Email</b></label>
<input
type="text"
placeholder="Enter Email"
name="email"
id="email"
required
/>
<label for="psw"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="psw"
id="psw"
required

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

/>
<label for="psw-repeat"><b>Confirm Password</b></label>
<input
type="password"
placeholder="Confirm Password"
name="psw-repeat"
id="psw-repeat"
required
/>
</div>
<div class="footer">
<p class="footer-text">
By creating an account you agree to our
<a href="#">Terms & Privacy</a>.
</p>
</div>
<button type="submit" class="sign-up-btn">Sign UP</button>
</div>
</div>
</form>
</body>
</html>

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Go to kishanflask.py file create a about page.

from flask import Flask


from flask import render_template
app = Flask(__name__)
@app.route("/")
def welcome():
return render_template('welcome.html')
#if __name__ =="__main__":
# app.run(debug=True)
#2nd action
@app.route("/subpage1")# url
def myfirstpage():
return render_template('register.html')
@app.route("/about")
def about():
return render_template('about.html')

About.html:
{% extends 'base.html' %}
{% block title %}
about page
{% endblock %}
{% block container %}
<h1>about page</h1>
<p>name: kishan</p>
{% endblock %}

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="styleasheet" type="text/css" href="../static/style.css">
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<h1>kishan's Flask Web Application</h1>
<div class = "container">
{% block container %}
{% endblock %}
</div>
</body>
</html>

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Go to kishanflask.py file and create a to-do list page.


from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def welcome():
return render_template('welcome.html')
#if __name__ =="__main__":
# app.run(debug=True)
#2nd action
@app.route("/subpage1")# url
def myfirstpage():
return render_template('register.html')
@app.route("/about")
def about():
return render_template('about.html')
@app.route("/todo")
def todo():
return render_template('todo.html')

todo.html

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
min-width: 250px;
}
/* Include the padding and border in an element's total width and height */
*{
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #eee;
font-size: 18px;
transition: 0.2s;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
background: #f9f9f9;
}
/* Darker background-color on hover */
ul li:hover {
background: #ddd;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #f44336;
color: white;
}
/* Style the header */
.header {
background-color: #f44336;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
/* Style the "Add" button */
.addBtn {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #bbb;
}
</style>
</head>
<body>
<div id="myDIV" class="header">
<h2 style="margin:5px">My To Do List</h2>
<input type="text" id="myInput" placeholder="Title...">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li>Hit the gym</li>
<li class="checked">Pay bills</li>
<li>Meet George</li>
<li>Buy eggs</li>
<li>Read a book</li>
<li>Organize office</li>
</ul>
<script>
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
</script>
</body>
</html>

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Demonstrating NumPy

Part 1(B1)
Aim. program to create 1-dimensional array and perform sorting.

Code:

print("Name:KisanKumar Akhilesh Goud Roll No:719")

import numpy as np

# id array= row vector


kishan_a1=np.array([10,20,30,40,50,60])
print("Numpy array a1= Row vector=",kishan_a1)

# ID array =column vector


kishan_a2=np.array([[10],[20],[30],[40],[50],[60]])
print("Numpy array a2= Row vector=",kishan_a2)

# create a ID array filled with o's


kishan_a3=np.zeros(10)
print("numpy array a3=",kishan_a3)

# create a ID array filled with one's


kishan_a4=np.ones(5)
print("numpy array a4=",kishan_a4)

# create a ID array with a specified range


kishan_a5=np.arange(25)
print("numpy array a5=",kishan_a5)

# create a ID array which is space linearly


kishan_a6=np.linspace(15,25,num=5)
print("numpy array a6=",kishan_a6)

# create an empty array with 1 element


kishan_a7=np.empty(2)
print("numpy array a7=",kishan_a7)

# Finding min And Max values


kishan_a8=np.array([1,2,3,4,5])
print("numpy array a8=",kishan_a8)

# convert a python list to a numpy array


kishan_list=[1,2,3,4,5]

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

list_toarray=np.array(kishan_list)
print("numpy array a8=", kishan_a8)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B2)
Aim: program to work with numpy data type.

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


#program to work with numpy data type

import numpy as np

arr1=np.array([1,2,3,4,5,6,7,8,9,10])
#INDEXING ONE ELEMENT IN THE ARRAY
index_add=arr1[5]
print("element sitting in the position of:",index_add)

#assign a new value in specific index


assign=arr1[5]=100
print("assigning the new value at position 5 is",assign)
#indexing more the one element
multi_index= arr1[np.array([0,5,6])]
print("multi element sitting in the position of:",multi_index)
#conditional indexing
con_var = (arr1>15)
print(con_var)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B3)
Aim: program to perform indexing and slicing ID Array.

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


import numpy as np

arr1=np.array([5,10,15,20,25,30,35,40])
#program to perform indexing and slicing ID Array
#slicing of ID array
#slicing method1:-[start:stop]-->[index of start:index of stop]
#a.[:]
print("slicing[:]",arr1[:])
#b.[value:]
print("slicing[3:]",arr1[3:])
#c.[:value]
print("slicing[:7]",arr1[:7])
#d.[2:5]
print("slicing[2:5]",arr1[2:5])

#slicing method 2-->[start:stop:step]


print("slicing with step[2:6:2]",arr1[2:6:2])

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B4)
Aim. program to create a multidimensional array 2d/3d.

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np

arr1=np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
print("two dimensional array:\n",arr1)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B5)
Aim. program to perform indexing and slicing a 2d array

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
twod_array = np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10],[10,11,12,13]])

#indering on 2D array -> [inden of row, index of column]


index_at = twod_array[0, 0]
print("Element at index [0, 0]: ", index_at)

# Find elements at index [1,2], [3,2] and [2,-1]


index_at = twod_array[1, 2]
print("Element at index [1, 2]: ", index_at)

index_at = twod_array[3, 2]
print("Element at index [3, 2]: ", index_at)

index_at = twod_array[2, -1]


print("Element at index [2, -1]: ", index_at)

# Slicing a 2D array - To slice an array we must specify which part of each dimension we
want to chop

#[ start position of row: stop position of row ,Start position of column: stop position of
column]

Slice_at = twod_array[:, :]
print("Slicing at index [0, 0]: ",Slice_at)
Slice_at = twod_array[:, 3]
print("Slicing at index [:, 3]: ",Slice_at)
Slice_at = twod_array[:, :1]
print("Slicing at index :, :1]: ",Slice_at)
Slice_at = twod_array[1:2, 0:3]
print("Slicing at index [1:2, 0:3]: ",Slice_at)
Slice_at = twod_array[1, :2]
print("Slicing at index [1, :2]: ",Slice_at)
Slice_at = twod_array[:, :-1]
print("Slicing at index [:, :-1]: ",Slice_at)
Slice_at = twod_array[1, -1]
print("Slicing at index [1, -1]: ",Slice_at)
Slice_at = twod_array[:3, :3]
print("Slicing at index [:3, :3]: ",Slice_at)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B6)
Aim. program to analysis array attribute

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


import numpy as np
arr1=np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
print("two dimensional array:",arr1)
#1.memory attributes
kishan_shape =arr1.shape
print("shape of array is:",kishan_shape)
kishan_size =arr1.size
print("size of array is:",kishan_size)
kishan_ndim =arr1.ndim
print("ndim of array is:",kishan_ndim)
kishan_itemsize =arr1.itemsize
print("itemsize of array is:",kishan_itemsize)
kishan_nbytes =arr1.nbytes
print("nbytes of array is:",kishan_nbytes)
kishan_base =arr1.base
print("base of array is:",kishan_base)
kishan_strides =arr1.strides
print("strides of array is:",kishan_strides)
kishan_data =arr1.data
print("data of array is:",kishan_data)
#2.datatype attributes
kishan_datatype =arr1.dtype
print("datatype of array is:",kishan_datatype)
#3.other attributes
kishan_transpose =arr1.T
print("transpose of array is:",kishan_transpose)
#convert arr1 to complex datatype
kishan_realno =arr1.real
print("real number in array is:",kishan_realno)
kishan_imageno =arr1.imag
print("imaginary number in array is:",kishan_imageno)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B7)
Aim. Program to create numpy array copy and numpy array view

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42

print("copy modified array", arr)


print("copied array", x)

arr = np.array([1, 2, 3, 4, 5])


x = arr.view()
arr[0] = 42

print("view modified array", arr)


print("view array", x)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B8)
Aim. program to perform operations thought mathematical and statistical method

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np

kishan_array2 = np.array([
[1, 0],
[0, 1]
])
# Mean
kishan_mean = np.mean(kishan_array2)
kishan_mean = np.mean(kishan_array2, axis=0)
print("Kishan_mean:\n ",kishan_mean)
kishan_mean1 = np.mean(kishan_array2, axis=1)
print("Kishan_mean1:\n ",kishan_mean1)
# sum
kishan_sum = np.sum(kishan_array2)
kishan_sum = np.sum(kishan_array2, axis=0)
print("Kishan_sum:\n ",kishan_sum)
kishan_sum1 = np.sum(kishan_array2, axis=1)
print("Kishan_sum1:\n ",kishan_sum1)
# cumsum-cumulative product
kishan_cumsum = kishan_array2.cumsum()
kishan_cumsum = kishan_array2.cumsum(axis=0)
print("Kishan_cumsum:\n ",kishan_cumsum)
kishan_cumsum1 = kishan_array2.cumsum(axis=1)
print("Kishan_cumsum1:\n ",kishan_cumsum1)
# cumprod
kishan_cumprod = kishan_array2.cumprod()
kishan_cumprod1 = kishan_array2.cumprod(axis=0)
print("Kishan_cumprod1:\n ",kishan_cumprod1)
kishan_cumprod = kishan_array2.cumprod(axis=1)
print("Kishan_cumprod:\n ",kishan_cumprod)
# Argmin And Argmax
kishan_argmin = np.argmin(kishan_array2)
print("Kishan_argmin:\n ",kishan_argmin)
kishan_argmax = np.argmax(kishan_array2)
print("Kishan_argmax:\n ",kishan_argmax)
# Variance and standard deviation
kishan_var = np.var(kishan_array2)
print("Kishan_var:\n ",kishan_var)
kishan_std = np.std(kishan_array2)
print("Kishan_std:\n ",kishan_std)
#min and max
kishan_max=np.max(kishan_array2)

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

print("Kishan_Max:\n ",kishan_max)
kishan_min=np.min(kishan_array2)
print("Kishan_Min:\n ",kishan_min)

output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B9)
Aim. program to perform file input and output with arrays

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")

import numpy as np

arr1=np.arange(15)
arr2=np.arange(8)
#saving array data on disk
a1=np.save('kpa_save',arr1)
#or
a2=np.save('kpa_save.npy',arr1)
print("file saved\n",a1)
print("file saved .npy\n",a2)

#loading array data from disk


k_load=np.load('kpa_save.npy')
print("loading from '.npy' file",k_load)

#saving array on disk in a incompressed archive


k_savez=np.savez('kpa_savez',a=arr1,b=arr2)
print("file saved in .npz\n",k_savez)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part 1(B 10)


Aim. program to perform manipulation

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")

#array manipulate
import numpy as np
a1=np.random.randn(2,4)
print(a1)

#basic operations -> copyto,check


b_arr=np.array([
0,1,0
])
print(b_arr)

a_array=np.array([1,1,0])
np.copyto(a_array,b_arr)
print("copyto array\n",a_array)

#2.change the shap of the array


#a.reshape
array1=np.arange(12)
print(array1)
ar_2d=array1.reshape(2,6)
print("reshaped array\n",ar_2d)
ar_3d=array1.reshape(2,2,3)
print("reshaped 3d array\n",ar_3d)

#difference between ravel and flatten


#ravel returns flatened array whereas flatten return a copy of array collapsed into 1dimension
specifally used nd arrays

#b.ravel
rav=np.ravel(ar_2d)
print("ravel function\n",rav)
print("np.ravel\n",np.ravel(ar_2d))
print("var\n",ar_2d)
#c.flatten
flat=ar_3d.flatten()
print("flatten array\n",flat)

#transpose like operations


trans=np.transpose(ar_2d)

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

print("transpose\n",trans)

#tiling array
til=np.tile((5,3),(5,6))
print("tile",til)

#expand dims
expand = np.expand_dims(ar_2d,axis=0)
print("expand ",expand)

expand1 = np.expand_dims(ar_2d,axis=1)
print("expand1",expand1)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 2
INTRODUCING MATPLOTLIB

Part A
Aim.  Program to generate a simple plot using matplotlib

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np
av_data = np.arange(20)
plt.plot(av_data)
plt.show()
value = np.linspace(0, 50, 100)
plt.plot(av_data, av_data, label="linear")
plt.plot(av_data, av_data**2, label="Quadratic")
plt.plot(av_data, av_data**3, label="Cubic")
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part B
Aim. Program to plot “Figures and Subplots”

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np
#Defining a time interval
time = np.arange(0., 3., 0.9)
# figure
k_fig=plt.figure()
# add_subplot --> will add subplots within the main plot (2 X 2 i.e.4 subplots)

ax1=k_fig.add_subplot(2, 2, 1)
plt.plot(np.random.randn(50).cumsum(),'k--' )
#plt.show()

ax2=k_fig.add_subplot(2, 2, 2)
plt.plot(time,time,'bs' )
#plt.show()

ax3=k_fig.add_subplot(2, 2, 3)
plt.plot(time,time**2,'g^' )
#plt.show()

ax4=k_fig.add_subplot(2, 2, 4)
plt.plot(time,time**3,'ro' )
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part C
Aim. Program to decorate a matplotlib plot using “Ticks, Labels, Legend and Title”

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np
# pyplot interface is designed for interactive use
# It consists of : xlim, xticks and xticklabels
fig =plt.figure()
ax =fig.add_subplot(2,1,1)
# randomly defining data values for the plot using cumlative frequency
ax.plot(np.random.randn(1000).cumsum())

# set_xticks --> will set the place along specified position on the xaxis
xticks = ax.set_xticks([0,250,500,750,1000])
yticks = ax.set_yticks([0,250,500,750,1000])
# set_xtickslabels --> will set the value as labels on those specified tick positions
xlabels = ax.set_xticklabels(['A','B','C','D','E'],rotation=0,fontsize="small")
ylabels = ax.set_yticklabels(['A','B','C','D','E'],rotation=0,fontsize="small")
# set_xlabel --> will set the label for X axis
ax.set_xlabel("values along x axis")
ax.set_ylabel("values along y axis")
# set_title --> will set the title for the plot
ax.set_title("Kisankumar Goud first plot")
# Title Style --> customizing the title
plt.title("KisanKumar Goud matplotlib",fontdict=None,loc='center',pad=None)
# ax.legend or plt.legend --> element that helps in identification of plot components
ax.legend()
# ax.legend(loc = 'best') --> best tells where to place the plot legend
# or
#plt.legend()
# If you do not want any element present in the plot to be involved in legend, we can pass no
label or label = '__nolegend__'
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part D
Aim. Program to plot a “Scatter Plot”

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


import matplotlib.pyplot as plt
import numpy as np
# 1. Plotting a scatter plot on some random data
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x,y)
plt.title("AV first scatter plot")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()
# 2. Plotting a scatter plot with plt
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.randn(100)
sizes = 1000*rng.randn(100)
plt.scatter(x,y,c=colors,s=sizes,alpha=0.3,cmap="viridis")
plt.show()
# 3. Plotting a scatter plot of age of a child and his/her height -->correlation
x = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.3, 2.7, 3.1, 3.6, 3.8, 4, 4.3, 4.5, 4.8])
plt.scatter(x,y)
plt.xlabel("age")
plt.ylabel("height")
plt.title("Plotting a scatter plot of age of a child and his/her height")

plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part E
Aim. Program to plot simple “Line Plots” and work with color & linestyles

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np
fig =plt.figure()
ax =plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x,np.sin(x))
plt.title("Line Plot")
plt.xlabel("linearlyspacevalues")
plt.ylabel("sin of x ")
plt.show()
# this will generate 2 different plots
# how to get both the plots in just one figure ???
plt.plot(x, np.cos(x))
plt.title("Line Plot 2")
plt.xlabel("Linearly Spaced Value")
plt.ylabel("Cosine of X")
plt.legend(),
plt.show()
# Adjusting line colors and styles
plt.plot(x, np.sin(x-5), color = 'blue', linestyle = 'solid')
plt.plot(x, np.sin(x+10), color = '#FFDD44', linestyle = 'dashed')
plt.plot(x, np.cos(x+2), color = 'chartreuse', linestyle = ':') # linestyle = dotted
plt.plot(x, np.cos(x-1), color = 'yellow', linestyle = '-.') # dashdot
plt.show()
# If no color is specified, Matplotlib will automatically cyclethrough a set of default colors
for multiple lines.
# Adjusting the Axes Limit of Plot
plt.plot(x,np.sin(x))
plt.plot(x, np.sin(x))
plt.xlim(-5, +5)
plt.ylim(-10, +10)
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part F
Aim. Program to plot “Bar Charts”, “Error Bars” and “Stack Charts”

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np

# Plotting a single data based bar chart


covid_data = [40, 25, 63, 80, 51, 13, 29]
plt.bar([1, 2, 3, 4, 5, 6, 7], covid_data)
plt.show()
# Add ticks, color, labels and title to the bar chart
values = ['Januray', 'February', 'March', 'April', 'May', 'June', 'July']
plt.xlabel('Months')
plt.ylabel('Number of COVID cases (in thousands)')
plt.xticks(range(len(covid_data)), values)
plt.title("Kisankumar First Matplotlib Bar Chart")
plt.bar(range(len(covid_data)), covid_data, color='green')
plt.show()
# Plotting multiple data based bar charts --> data is real -->collected from WHO
num = 5
covid_data_2020 = (20, 1800, 8782, 18641, 61242)
covid_data_2021 = (72000, 401993, 127510, 48786, 41831)
ind = np.arange(num)
width = 0.4
values = ('March', 'April', 'May', 'June', 'July')
plt.xlabel('Months of 2020 and 2021')
plt.ylabel('Number of COVID cases')
plt.xticks(ind + width / 2, values)
plt.legend(loc='best')
plt.title("Multi Data Based Matplotlib Bar Chart")
plt.bar(ind, covid_data_2020, width)
plt.title("Multi Data Based Matplotlib Bar Chart")
plt.bar(ind, covid_data_2020, width, color='green', label="COVID in 2020")
plt.bar(ind + width, covid_data_2021, width, color='blue', label="COVID in 2021")
plt.show()
# Home Work --> Error Bars
# Plotting stacked bar charts
data_a = [3, 6, 8, 10, 12]
data_b = [4, 8, 12, 16, 20]
num = range(5)
plt.bar(num, data_a, color='b')
plt.bar(num, data_b, color='r', bottom=data_a)
plt.show()
# Plotting stacked bar charts through 2D matrix data
values = ['Person A', 'Person B', 'Person C', 'Person D', 'Person E']

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

data_1 = np.array([3, 6, 8, 10, 12])


data_2 = np.array([4, 8, 12, 16, 20])
data_3 = np.array([1, 1, 1, 1, 1])
plt.bar(ind, data_1, width=0.8, label='Product 1', color='yellow', bottom=data_2 + data_3)
plt.bar(ind, data_2, width=0.8, label='Product 2', color='pink', bottom=data_3)
plt.bar(ind, data_3, width=0.8, label='Product 3', color='purple')

plt.xticks(ind, values)
plt.ylabel(" ")
plt.xlabel(" ")
plt.legend(loc="best")
plt.title("kisanKumar Goud Stacked Bar Chart")
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part G
Aim. Program to plot “Histogram”

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)
plt.hist(data, bins = 'auto', alpha = 0.7, color = 'steelblue', edgecolor ='none');
plt.grid(axis = 'y', alpha = 0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title("Kisankumar Normal Distribution Histogram")
plt.show()
# Histogram 2
data1 = np.random.normal(0, 0.8, 1000)
data2 = np.random.normal(-2, 1, 1000)
data3 = np.random.normal(3, 2, 1000)
plt.show()

output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part H
Aim. Program to use text and annotation on the plots

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import matplotlib.pyplot as plt
plt.plot([10,20,30,40] ,marker="o")
ax=plt.gca()
print(plt.text(0.5,30,"HELLO"))
print(plt.ylim())
plt.show()

Ouptut.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part I
Aim. Saving plots to file

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 100, 100)
y = np.sin(2*np.pi*x)
z = np.cos(2*np.pi*x)
plt.plot(x,y, label='sin')
plt.plot(x,z, label='cos')
plt.xlabel('time [s]')
plt.ylabel('signal [v]')
plt.legend()
plt.show()
plt.savefig("plot.png")

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part J

Aim. Plotting function in pandas 

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 1. Using pd.Series
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
plt.title("Kishan Pandas Series")
plt.show()
# 2. Using pd.DataFrame
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0))
columns = ['A', 'B', 'C', 'D']
index = np.arange(0, 100, 10)
df.plot()
plt.title("kishan Pandas Dataframe")
plt.show()

# 3. Plotting bar plot using data from pd.Series


s.plot.bar(ax=plt.axes, color='k', alpha=0.7); # normal bar chart
s.plot.bar(ax=plt.axes[1], color='k', alpha=0.5) # horizontal bar chart
s.plot()
plt.title('Kishan\'s pd.series')

plt.show()
# 4. Example
dataframe = pd.DataFrame({
'Name': ['Jack','Jill','Amy','Elona','Sherlock','Will','Erica'],
'Age': [10, 12, 9, 15, 8, 20, 17],
'State': ['Mumbai','Bangalore','Indore','Panjim','Hyderabad','Texas','Machester'],
'No_Kids': [2, 0, 0, 3, 2, 1, 4],
'No_Cars': [5, 1, 0, 5, 2, 2, 3]
})
plt.title("Kishan's pd.dataframe")
plt.show()
# preparing scatter plot from dataframe
dataframe.plot(kind = 'scatter', x = 'no_of_kids', y = 'no_of_pets', color = 'red')

plt.show()
# preparing simple line plot from dataframe
dataframe.plot(kind = 'line', x = 'Name', y = 'Age', color = 'yellow')
plt.show(

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

# preparing histogram from dataframe


dataframe[['age']].plot(kind = 'hist', bins = [0,20,40,60,80,100], rwidth = 0.8),
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 3
Part A
Aim. Program to use series and data frames.

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


import pandas as pd
import numpy as np
# Series --> one dimensional labelled array --> data, index(list of labels)(optional)
av_series =pd.Series(np.arange(10,30,5)) # data in the form of numpy series
av_series = pd.Series(10)# data in the form of scalar value
av_series = pd.Series(dict) # data in the form of dictionary
av_obj =pd.Series([1,8,3,0,5])
print("Result of series av_obj : \n", av_obj)
# Array values of the above defined series object
print("Array representation : ", av_obj.values)
# Index values of the above defined series object
print("Index representation : ", av_obj.index)
# Defining a series with a user specified index --> labelled index
array = [11, 22, 33, 44, 55]
av_obj2 = pd.Series(array, index = ['a', 'g', 'c', 'z', 'i'])
print("Result of series av_obj2 :\n", av_obj2)
print("Array representation : ", av_obj2.values)
print("Index representation : ", av_obj2.index)
# Operations on series object
av_obj2['i'] = 66# assigning a new value on already existing index
av_obj2['e'] =77 # creating a new entry in the series
print("Indexing of series : ", av_obj2)
print("Conditional indexing : ", av_obj2[av_obj2 > 22])
print("Scalar mulitplcation : ", av_obj2*10)
# Creating series from python dictionary
av_dict = {
'India' : 12,
'United Kingdom' : 20,
'United States' : 112,
'China' : 20,
'Japan' : 10
}
av_obj3 = pd.Series(av_dict)
print("AV Object 3 series :\n", av_obj3)
print("Has any null value ? \n", pd.isnull(av_obj3))
print("If not null return True, else False\n",
pd.notnull(av_obj3))

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

print("av_obj3.isnull --> ", av_obj3.isnull())


# Assigning a name to the series using "name" attribute
av_obj3.name = 'countries'
av_obj3.index.name = 'state'
print("av_object 3\n",av_obj3)
# Renaming the series using "rename" attribute
av_obj_new = av_obj3.rename("List of Countries")
# Data Frames --> two dimensional data format -->
# labelled --> table or excel sheet --> data, columns(optional) and index(optional)
av_data2 = {
"A" : pd.Series([1, 2, 3]),
"B" : pd.Series([4, 5, 6]),
"C" : pd.Series([7, 8, 9])}
av_data = {
'State': ['Maharashtra', 'Banglore', 'Goa', 'Indore', 'Vadodra','Hyderabad'],
'Year': [2000, 2001, 2002, 2001, 2002, 2003],
'Population': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
frame = pd.DataFrame(av_data)
print("Data Frame formed from av_data\n", frame)
frame = pd.DataFrame(av_data, columns = ['Year', 'State','Population'])
print("Data Frame formed from av_data\n", frame)
# Displaying the head of the dataframe
print("Head of the data frame\n",frame.head())
# Displaying the tail of the dataframe
print("Tail of the data frame\n",frame.tail())
frame = pd.DataFrame(av_data, columns = ['Year', 'State','Population', 'Medals'], index =
["a", "b", "c", "d", "e", "f"])
print("\nDisplaying columns of the above data frame\n",frame.columns)
# Retrieving the values of a column from the data frame --> Column selection
print("\nYear Column Column selection \n", frame['Year']) # only one column selected
# Inserting a bool valued column
frame['Result'] = frame['Year'] > 2001
print("\nConditional column : \n", frame)
# Filling a static saclar value in the column
frame['Medals'] = [10, 12, 15, 63, 96, 78]
print("\nAssigning a static value to the Medals column : \n", frame)
# Creating a column in the data frame
frame['New Column'] = np.arange(6)
# Displaying the complete data frame in the form of values
print("\nValues from dataframe 'frame'\n", frame.values)
# Selection of a row with indexing
print("Selecting the row with index 'c' : \n", frame.loc["c"]) # one row selection

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part B
Aim. Program to use multi-indexing or hierarchical indexing

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import pandas as pd
import numpy as np
data = [('ICC World Cup', 2015), ('ICC World Cup', 2019),
('FIFA World Cup', 2014), ('FIFA World Cup', 2018),
('Olympics', 2020), ('Olympics', 2024)]
viewers = [33871648, 37253956,
18976457, 19378102,
20851820, 25145561]
To_series =pd.Series (viewers,index=data)
print("\nSeries conversion of data : \n", To_series)
print("\nIndex of the series : \n", To_series.index.names)
print("Slicing the multi index object : ", To_series[('ICC World Cup', 2015):('Olympics',
2020)])
print("Indexing the multi index object : ", To_series[[i for i in To_series.index if i[1]==2018
]])
data =pd.MultiIndex.from_tuples(data)
print(data)
To_series = To_series.reindex(data)
print(To_series)
# Indexing a multi-index object
print("Indexing : ", To_series['Olympics', 2024])

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part C
Aim. Program to concatenate, append, join, merge and compare the data frames

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import pandas as pd
import numpy as np
dataframe1 = pd.DataFrame(
{
"Number" : [1, 2, 3, 4, 5, 6],
"Alphabets" : ["A", "B", "C", "D", "E", "F"]
},
index = np.arange(6))
dataframe2 = pd.DataFrame(
{
"Number" : [6, 7, 8, 9, 10],
"Alphabets" : ["F", "G", "H", "I", "J"]
},
index = np.arange(5, 10))
# Using concatenate --> , by default if join = outer then union --> if join = inner then
intersection
dataframes = [dataframe1, dataframe2]
dataframe_concat = pd.concat(dataframes)
print("Concatenation of two dataframes results into\n",
dataframe_concat)
dataframe_concat = pd.concat(dataframes, axis = 0, join = "outer", keys = ["df1", "df2"]) #-->
default join is outer
print("Concatenation of two dataframes results using outer join\n", dataframe_concat)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part D
Aim. Program to perfrom data grouping and data aggregation
Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import pandas as pd
import numpy as np
data_passenger = pd.DataFrame(
{
'PassengerId' : ['415', '270', '873', '404', '516'],
'Name' : ['Mary', 'Leo', 'Arthur', 'James', 'Silvia'],
'Age' : [15, 30, 45, 60, 75],
'PassengerClass' : [1, 1, 3, 1, 2],
'Gender' : ['F', 'M', 'M', 'M', 'F']
}
)
print("Data Frame\n", data_passenger)
# A. Data Grouping
# groupby --> helps in analysing the data of a particular category # default axis is 0
data_group_gender = data_passenger.groupby("Gender")
print("Grouping the data based on the column named as 'Gender'\n", data_group_gender)
print(data_group_gender.head())
# groupby sorting --> group keys are sorted
my_data = pd.DataFrame(
{
"X": ["B", "B", "A", "A", "C"],
"Y": [1, 2, 3, 4, None]
})
print("\nGrouping by sort : \n", my_data.groupby(["X"], sort =
False).head())
# groupby dropna --> default NA values are excluded
print("\nGrouping by dropna : \n",my_data.groupby(by = ["X"], dropna = True).head())

#1. Get the data type object


#2. Retrieve the number of groups existing
#3. Get the objects of the groups
# to retrieve one of the created groups within the dataframes
print("\nGroups created within 'data_group_gender' (male group) : \n",
data_group_gender.get_group('M'))
print("\nGroups created within 'data_group_gender' (female group) : \n",
data_group_gender.get_group('F'))
# B. Data Aggregation
# performing computations on the already grouped data
# to compute the max values
print("Performing aggregation on : \n", data_group_gender.Age.max())

# to display the first and the last entry in the dataframe


print("\nFirst Entry : ", data_group_gender.first())
print("\nLast Entry : ", data_group_gender.last())

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part E
Aim. Program to work with time series and date functionality

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import pandas as pd
import numpy as np
import datetime
# parsing time series information from various sources and formats
r_date = pd.to_datetime(
["31/8/2021", np.datetime64("2021-08-31"),
datetime.datetime(2021, 8, 31)]
)
print("\nDate Time : ", r_date)
# Generating sequences of fixed frequency dates and time spans
r_date = pd.date_range("2021-08-31", periods = 10, freq ='H')
print("\nDatetime with hourly frequency : ", r_date)
# Manipulating and converting date times with time zone information
r_date_utc = r_date.tz_localize("UTC")
print("\nDate Time UTC Manipulation : ", r_date_utc)
r_date_us = r_date_utc.tz_convert("US/Pacific")
print("\nDate Time US/Pacific Conversion : ", r_date_us)
# Add one business day (Friday --> Monday)
friday = pd.Timestamp("2021-09-03")
business_day = friday + pd.offsets.BDay()
print("\nNext working day i.e. business day is ",
business_day.day_name())

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part F
Aim. Program to handle missing data

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
from pandas.core import frame
import pandas as pd
import numpy as np
data_student = pd.DataFrame(
{
'Roll' : [101, 102, 103, 104, 105, 106, 107, 108, np.nan,
110],
'Div' : ['A', 'B', 'A', 'B', 'A', 'B', None, 'A', 'B', None],
'Age' : [18, 19, 18, 20, 21, 18, 18, 19, 20, 19],
'Marks' : [5, 8, 5, None, 0, 5, 9, 10, 1, np.nan],
'Gender' : ['F', None, 'M', 'M', 'M', 'F', 'F', None, 'M',
'F']
}
)
print("\nStudent dataframe is as follows : \n", data_student)
# Detecting whether missing values are present in the above data frame or no
missing_isna = data_student.isna()
print("\nMissing data within the complete data frame found with isna : ", missing_isna)
missing_notna = data_student.notna()
print("\nMissing data within the complete data frame found with notna : ", missing_notna)
# Detecting whether missing values are present in one of the columns of the dataframe
print("\nDetecting missing values in the division columns : \n",
pd.isna(data_student["Div"]))
# Performing operations with missing data
average_class_marks = data_student["Marks"].sum()
print("\nArithmetic operation on data frame : ", average_class_marks)
cumulative_class_marks = data_student["Marks"].cumsum(skipna = True)
print("\nArithmetic operation on data frame : \n",cumulative_class_marks)
# Filling missing values using fillna
print("\nFill NA within the dataframe with '0' : \n",data_student.fillna(0))
print("\nFill NA in roll number column with specific text : \n",
data_student["Roll"].fillna("No roll number"))
fill_mean = data_student["Marks"].fillna(data_student["Marks"].mean())
print("\nFilling vacant values with mean : \n", fill_mean)
# Filling using "where"
fill_mean2 = data_student["Marks"].where(pd.notna(data_student["Marks"]),
data_student["Marks"].mean())

print("\nFilling vacant values with mean : \n", fill_mean2)

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Output.
s

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part G
Aim. Program to calculate descriptive and summary statistics on a dataset
Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import pandas as pd
titanic = pd.read_csv("titanic.csv")
# Titanic Dataset From Here
#https://github.com/pandas-dev/pandas/blob/master/doc/data/titanic.csv
print("Head of titanic dataset : ",titanic.head() )
# Descritpive and summary statistic methods are as follows
# count, describe, min, max, argmin, argmax, quantile, sum, mean, median, var, std, skew,
kurt
# Standard deviation and variance of age of passengers on titanic
print("Average : ", titanic["Age"].mean())
#Similarly, find standard deviation and variance
# Median age and ticket fare price of the titanic passengers
print("Median : ", titanic[["Age", "Fare"]].median())
# Complete set of descriptive statistics - describe()
print("Describe : ", titanic[["Age", "Fare"]].describe())
# Average age for male versus female Titanic passengers
print("Average age for males vs females : ", titanic[["Sex", "Age"]].groupby("Sex").mean())
print("Count using groupby : ", titanic["Pclass"].count())

output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 4
INTRODUCTION TO SCIPY
PART A
Aim. Creating special functions using SciPy

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import scipy
from scipy import special

#bdtr(k = no .of successes, n = no. of events, p = prob of successes)


binomial = scipy.special.bdtr(2, 4, 0.5)
print("Binomial distribution cumulative distribution function : ", binomial)

#fdtr(dfn = positive floating, dfd = non-negative floating, arguments)


fdistribution = scipy.special.fdtr(10.5, 15.8, 4.0)
print("F cumulative distribution function : ", fdistribution)
#pdtr(k = real argument, m = event rare, out = None)
poisson = scipy.special.pdtr(22, 7)
print("Poisson cumulative distribution function : ", poisson)

# df = degree of freedom > 0


studentt = scipy.special.stdtr(6, 40)
print("Student t distribution cumulative distribution function : ", studentt)

# Factorial of a number
factorial = scipy.special.factorial(8)
print("Factorial of the above entered number is ", factorial)

cuberoot = scipy.special.cbrt(512)
print("Cube root of above entered number is ", cuberoot)

# Conversion from degree to radian


degtorad = scipy.special.radian(90, 10, 0)
print("Degree to Radian : ", degtorad)

cosine = scipy.special.cosdg(45)
print("Cosine of 45 : ", cosine)

# similarly, we can find sindg, tandg, cotdg, cosecdg


round = scipy.special.round(39.578640)
print("Rounding the above vlaue to nearest integer : ", round)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part B
Aim. Performing integration using SciPy.

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
import scipy.integrate as integrate
import scipy.special as special
from scipy.integrate import quad, dblquad

# quad --> helps in defining single definite integration


# dblquad --> helps in defining double integration
# triple integartion -->
# n integration --> nquad
result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5)
print("Result of integration : ", result)
def I(n):
return dblquad(lambda t, x: np.exp(-x*t)/t**n, 0, np.inf, lambda x: 1, lambda x: np.inf)

print("I(1) = ", I(1))


print("I(4) = ", I(4))
area = dblquad(lambda x, y: x*y, 0, 0.5, lambda x: 0, lambda x: 1-2*x)
print("Area : ", area)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part C
Aim. Interpolation using SciPy

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
one_variable = np.linspace(0, 20, num = 7, endpoint = True)
two_variable = np.cos(-one_variable**2/9.0)
f1 = interp1d(one_variable, two_variable)
f2 = interp1d(one_variable, two_variable, kind = 'cubic')
xnew = np.linspace(0, 10, num = 41, endpoint = True)
plt.plot(one_variable, two_variable, 'o', xnew, f1(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data points', 'linear plotting', 'cubic plotting'], loc = 'best')
plt.show()
# Setting up fake data
x = np.linspace(0, 10 * np.pi, 20)
y = np.cos(x)
# Interpolating data
fl = interp1d(x, y, kind='linear')
fq = interp1d(x, y, kind='quadratic')
# x.min and x.max are used to make sure we do not go beyond the boundaries of the data for
the interpolation.
xint = np.linspace(x.min(), x.max(), endpoint = True)
yintl = fl(xint)
yintq = fq(xint)
plt.plot(x, y, 'o', xint, yintl, '-', xint, yintq, '--')
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part D
Aim. Performing signal processing using SciPy

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt

image = misc.face(gray = True)

# defining convolution matrix


w = np.zeros((300, 450))
w[8][15] = 1.0
w[100][63] = 1.0

# applying convolution on the image


image_new = signal.fftconvolve(image, w)

plt.figure()
plt.imshow(image)
plt.title('Original image')
plt.show()

plt.figure()
plt.imshow(image_new)
plt.title('Filtered image')
plt.show()

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part E
Aim. Performing linear algebriac calculations through SciPy

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
import numpy as np
from scipy import linalg

# Amxn Bnxp = Cmxp


A = np.mat('[1 2; 3 4]') # m = 2, n = 2
# A = np.array([[1,2],[3,4]])

print("Matrix A : \n", A)
print("Result of A.I i.e. inverse : \n", A.I)

b = np.mat('[5 6]') # m = 1 , n = 2
print("Matrix b : \n", b)

print("Transpose of b : \n", b.T) # m = 2, n = 1

print("Result of A*b.T : \n", A*b.T)


inverse = linalg.inv(A)
print("Inverse of A : \n", inverse)

determinant = linalg.det(A)
print("Determinant of A : \n", determinant)

default_norm = linalg.norm(A)
# frobenius norm = sqrt((1^2 + 2^2 + 3^2 + 4^2))
print("Default/Frobenius Norm of A : \n", default_norm)

B = np.array([5, 0, 7])
L1_norm = linalg.norm(B, 1)
# l1 norm = adds all values
print("L1 norm of B : \n", L1_norm)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 5
SEARCH ALGORITHM
Part A
Aim. Program to implement depth first search algorithm

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
print("Program to solve the below given graph traversal problem through Depth First
Search")

print("Searching Across Depth Top to Bottom All Levels at Once")

# Depth First Tree Search Algorithm


# Search the deepest nodes in the search tree first.
# Search through the successors of a problem to find a goal.
# The argument frontier should be an empty queue.
# Repests infinitely in case of loops.

#Depth First Graph Search Algorithm


# Search the deepest nodes in the search tree first.
# Search through the successors of a problem to find a goal.
#The argument frontier should be an empty queue.
#Does not get trapped by loops.
# If two paths reach a state, only use the first one.

explorednode= set()

def DepthFirstSearch (graph, startnode, explorednode):


if startnode is None:
print("Start Node is None or it is a leaf node!")
return

if startnode not in graph:


print("Start Node is Not Present in the Current Graph!")
return
if startnode not in explorednode:
print("Current Node Being Visited is",startnode)
explorednode.add(startnode)
for nextnode in graph[startnode]:
DepthFirstSearch(graph, nextnode, explorednode)
return explorednode
#Graph with directed edges and the edges have no weights # Two ways of representing
Graphs
#1.Adjacency Matrix (numpyarrays) eachrownode & eachcolumnchildofnode
# Home Work Practical 5A -> use numpy 2D matrix as a graph --> Create a 2D matrix
#2.AdjacencyList

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

av_graph_one={
'A': set(['B', 'C']),
'B': set(['D', 'E']),
'C': set(['F']),
'D': set([]),
'E': set(['F']),
'F': set([])
}

av_graph_two={
'0': set(['1', '2']),
'1': set(['4', '5']),
'2': set(['3','5']),
'3': set(['6']),
'4': set(['7']),
'5': set(['3','6']),
'6': set(['7']),
'7': set([])
}

av_graph_three= {
'Amy': set(['Jack', 'Jill','Joana']),
'Jack': set(['Lucy']),
'Lucy': set([]),
'Jill': set(['Cindy','Camilla']),
'Cindy': set(['Eleven','Emma']),
'Joana': set(['Will']),
'Camilla': set([]),
'Will': set([]),
'Eleven': set([]),
'Emma': set([])
}

search_graph = av_graph_two
print("\n Problem Graph is as follows......\n", search_graph)

start_search_at ='0'
# assigning the start node as a variable

print("\n Solution Path For the Above problem using Depth First graph Search is as follows :\
n")
DepthFirstSearch(graph=search_graph,startnode=start_search_at,explorednode=explorednod
e)

output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part B
Aim. Program to implement breadth first search algorithm

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
print("Program to solve the below given graph traversal problem through Depth First
Search")
print("Searching Across Depth --> left to right --> One Levels at a Time")
#Breadth first tree search algorith.
#search the shallowest nodes in the search tree first.
#search through the successors of a problem to find a goal.
#the argument frontier should be an empty queue.
#Repeats infinitely in case of loops
#Breadth First Graph Search Algorith.
#Search the deepest nodes in the search tree first.
#search through the successors of a problem to find a goal.
#the argument frontier should be an empty queue.
#does not get trapped by loops.
explorednode = []
def BreadthFirstSearch(graph, startnode, explorednode):
if startnode not in graph:
print("Node is Not a Part of This Current Graph!")
# Defining explored node as a list of nodes already explored while traversing
nodequeue = [startnode] # Queue --> FIFO --> First In First Out
while len(nodequeue) > 0:
currentnode = nodequeue.pop(0)
print("\nCurrent Visited Node is ", currentnode, end="")
if currentnode is not explorednode:
explorednode.append(currentnode)
adjacentnode = graph[currentnode]
for node in adjacentnode:
if node in explorednode:
return nodequeue.append(node)
return explorednode

akp_graph_one = dict() #Defining graph as a python dictionary


akp_graph_one["A"] = ["B","G", "D"]
akp_graph_one["B"] = ["A","F", "E"]
akp_graph_one["C"] = ["F","H"]
akp_graph_one["D"] = ["A","F"]
akp_graph_one["E"] = ["B","G"]

akp_graph_one["F"] = ["B","D", "C"]


akp_graph_one["G"] = ["A","E"]
akp_graph_one["H"] = ["C"]
akp_graph_two = {
'Amy': set(['Jack', 'Jill', 'Joana']),

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

'Jack': set(['Lucy', 'Amy']),


'Lucy': set([ 'Jack']),
'Jill': set(['Cindy', 'Camilla']),
'Cindy': set(['Eleven', 'Emma']),
'Joana': set(['Will', 'Lucy']),
'Camilla': set(['Jill']),
'Will': set(['Joana']),
'Eleven': set([ 'Cindy']),
'Emma': set([ 'Cindy'])
}
search_graph = akp_graph_one
print("\n Problem Graph is as follows......\n", search_graph) #assigning thestart node as a
variable
start_search_at = "A"
print("\nSolution Path For the Above Problem using Breadth First Graph Search is as follows
: \n")
solution = BreadthFirstSearch(search_graph, start_search_at, explorednode)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 6
Aim. Program to solve the tower of Hanoi problem

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
print("Program to solve the tower of hanoi problem")
print("Recursion Approach")

def TowerOfHanoi(number_of_disks, sourcePole, intermediatePole, destinationPole):


if number_of_disks == 0:
print("No disks left to solve the problem")
return
if number_of_disks == 1:
print("Moving Circular Disk 1 from", sourcePole, "to", destinationPole)
return
TowerOfHanoi(number_of_disks - 1, sourcePole, destinationPole, intermediatePole)
print("Moving Circular Disk", number_of_disks, "from", sourcePole, "to", destinationPole)
TowerOfHanoi(number_of_disks - 1, intermediatePole, sourcePole, destinationPole)

no_disk = int(input("Enter the number of circular disks you want in the tower of hanoi
problem: "))
TowerOfHanoi(
number_of_disks=no_disk,
sourcePole="A",
intermediatePole="B",
destinationPole="C")

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 7
Part A
Aim. Write A Program To Implement Alpha Beta Search.

Code.

print("Name:KisanKumar Akhilesh Goud Roll No:719")


# For a two player game, minimax algorithm is such a tactic which uses the fact # that the
two players are working towards opposite goals to make predictions about # which future
states will be reached as the game progresses, and then proceeds # accordingly to optimize its
chance of victory. The theory behind minimax is that # the algorithm's opponent will be
trying to minimize whatever value the algorithm # is trying to maximize (hence, "minimax").
Thus, the computer should make the move # which leaves its opponent capable of doing the
least damage.
# ---------Declaration of function used in the program-----------
# alphabeta(input, start, upper, lower)
# Where: input is a list form input tree. See example in this file, start is the root node number.
So, either 0 or 1 (0 if root is MAX, 1 if root is MIN) upper is the upper limit for Alpha, lower
is the lower limit for Beta. The function returns the root alpha and beta values, as well as the
result, and the number of 'prunings' that took place.

Data_Tree = [[[1, 2, 3], [-1, -2, -3]],


[[-4, -5, -6], [4, 5, 6]],
[[7, 8, 9], [-7, -8, -9]]]

# Declaring the root node as 0


Root_Node = 1
# Declaring number of prunings done initially as 0
Pruned = 0

def Child_Nodes(branches, depth_tree, alpha_value, beta_value):


global Pruned
global Root_Node
global Data_Tree
i=0

for every_child in branches:


if type(every_child) is list:
(a, b) = Child_Nodes(every_child, depth_tree + 1, alpha_value, beta_value)
if depth_tree % 2 == 1:
if a < beta_value:
beta_value = a
else:
beta_value = beta_value
else:

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

if b > alpha_value:
alpha_value = b
else:
alpha_value = alpha_value
if depth_tree % 2 == 0:
branches[i] = alpha_value
else:
branches[i] = beta
i += 1
else:
if depth_tree % 2 == 0 and alpha_value < every_child:
alpha_value = every_child
if depth_tree % 2 == 1 and beta_value > every_child:
beta_value = every_child
if alpha_value >= beta_value:
Pruned += 1
break

if depth_tree == Root_Node:
if Root_Node == 0:
Data_Tree = alpha_value
else:
Data_Tree = beta_value
return (alpha_value, beta_value)

# Remember - Alpha is the minimum upper bound of possible solutions meaning a node's
value to be accepted and updated with max value must be atleast α i.e. greater than Alpha
will work but not less
# Remember - Beta is the maximum lower bound of the possible solutions meaning a node's
value to be accepted and updated with min value must be atmost β i.e. less than Beta will
work but not greater

def AlphaBeta(Search_Tree, Start_Node, Upper_Bound, Lower_Bound):


global Data_Tree
global Root_Node
global Pruned
(alpha_value, beta_value) = Child_Nodes(Data_Tree, Start_Node, Upper_Bound,
Lower_Bound)

if __name__ == "__main__":
print("Best value of Alpha : ", alpha_value)
print("Besy value of Beta : ", beta_value)
print("How many times was the Data_Tree prunded ? --> ", Pruned)
print(
"Number of nodes of the search tree that are to be evaluated by min max algorithm
after alpha beta pruning has been applied on it = ",Data_Tree)

print("\n***User defined MAX and MIN value***")

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

upperbound = int(input("Enter the Minimum Upper Bound value : "))


lowerbound = int(input("Enter the Maximum Lower Bound value : "))

print("\n***Applying alpha beta pruning on the tree***")


AlphaBeta(Search_Tree=Data_Tree, Start_Node=Root_Node, Upper_Bound=upperbound,
Lower_Bound=lowerbound)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Part B
Aim. Program to solve water jug problem

Code.
def SolvingWaterJugProblem(Jug1, Jug2):

Capacity_Jug1 = 5
Capacity_Jug2 = 7
Resultant_Water = 4

print("Water in Jug 1 = %d \tWater in Jug 2 = %d" % (Jug1, Jug2))


if Jug2 is Resultant_Water:
return
elif Jug2 is Capacity_Jug2:
SolvingWaterJugProblem(0, Jug1)
elif Jug1 != 0 and Jug2 == 0:
SolvingWaterJugProblem(0, Jug1)
elif Jug1 is Resultant_Water:
SolvingWaterJugProblem(Jug1, 0)
elif Jug1 < Capacity_Jug1:
SolvingWaterJugProblem(Capacity_Jug1, Jug2)
elif Jug1 < (Capacity_Jug2 - Jug2):
SolvingWaterJugProblem(0, (Jug1 + Jug2))
else:
SolvingWaterJugProblem(Jug1 - (Capacity_Jug2 - Jug2), (Capacity_Jug2 - Jug2) + Jug2)
print("Generally, initial amount of Water in Both Jug i.e.Jug 1 = 0 and Jug 2 = 0")

# Taking user input for initial amount of water in jug 1 and jug 2
Water_in_Jug1 = int(input("\nEnter the initial capacity of first Water jug : "))
Water_in_Jug2 = int(input("\nEnter the initial apacity of the second water jug : "))

print("Let's start solving the water jug problem.....")


SolvingWaterJugProblem(Water_in_Jug1, Water_in_Jug2)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

Practical 8
Aim. Traveling Salesperson/Salesman Problem

Code.
print("Name:KisanKumar Akhilesh Goud Roll No:719")
# **Practical 8 Traveling Salesperson/Salesman Problem**
#“Given a list of cities and the distances between each pair of cities, what is the shortest
possible route that visits each city and returns to the origin city?”
import six
import sys
sys.modules['sklearn.externals.six']=six
import mlrose
import numpy as np

# Create list of city coordinates


coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]

# Initialize fitness function object using coords_list


fitness_coords = mlrose.TravellingSales(coords = coords_list)

# Create list of distances between pairs of cities


dist_list = [(0, 1, 3.1623), (0, 2, 4.1231), (0, 3, 5.8310), (0, 4, 4.2426),\
(0, 5, 5.3852), (0, 6, 4.0000), (0, 7, 2.2361), (1, 2, 1.0000),\
(1, 3, 2.8284), (1, 4, 2.0000), (1, 5, 4.1231), (1, 6, 4.2426),\
(1, 7, 2.2361), (2, 3, 2.2361), (2, 4, 2.2361), (2, 5, 4.4721),\
(2, 6, 5.0000), (2, 7, 3.1623), (3, 4, 2.0000), (3, 5, 3.6056),\
(3, 6, 5.0990), (3, 7, 4.1231), (4, 5, 2.2361), (4, 6, 3.1623),\
(4, 7, 2.2361), (5, 6, 2.2361), (5, 7, 3.1623), (6, 7, 2.2361)]
# Initialize fitness function object using dist_list
fitness_dists = mlrose.TravellingSales(distances = dist_list)
problem_fit = mlrose.TSPOpt(length = 8, fitness_fn = fitness_coords, maximize = False)

coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]
problem_no_fit = mlrose.TSPOpt(length = 8, coords = coords_list, maximize=False)

# Solve problem using the genetic algorithm


best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state = 2)

print('The best state found is: ', best_state)

print('The fitness at the best state is: ', best_fitness)

Output.

ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719

ARTIFICIAL INTELLIGENCE

You might also like