AI Practicals
AI Practicals
AI Practicals
719
Practical No. 1
Django Framework
Aim: DJANGO
Creating a project
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
Go In APPom1/Views.py And Create a Function Welcome And Learn Which Returns HTTP
Response And Render
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
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
ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719
<!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
<!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
Go to register/urls .py
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'
]
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.
ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719
ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719
</body>
</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
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
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:
import numpy as np
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.
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)
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.
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])
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]])
index_at = twod_array[3, 2]
print("Element at index [3, 2]: ", 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.
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.
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)
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
Code.
#array manipulate
import numpy as np
a1=np.random.randn(2,4)
print(a1)
a_array=np.array([1,1,0])
np.copyto(a_array,b_arr)
print("copyto array\n",a_array)
#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)
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.
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
ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719
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
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()
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
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.
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
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())
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())
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
# 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)
cosine = scipy.special.cosdg(45)
print("Cosine of 45 : ", cosine)
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
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
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
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)
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")
explorednode= set()
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
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
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")
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.
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
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)
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
Part B
Aim. Program to solve water jug problem
Code.
def SolvingWaterJugProblem(Jug1, Jug2):
Capacity_Jug1 = 5
Capacity_Jug2 = 7
Resultant_Water = 4
# 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 : "))
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
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)
Output.
ARTIFICIAL INTELLIGENCE
TYBSC.IT Semester 5 Kisankumar Akhilesh Goud Roll no. 719
ARTIFICIAL INTELLIGENCE