Ai Lab Rec March2020
Ai Lab Rec March2020
NO:
8 PUZZLE PROLEM
DATE:
AIM:
ALGORITHM:
PROGRAM:
import random
import math
_goal_state = [[1,2,3],
[4,5,6],
[7,8,0]]
def index(item, seq):
except:
return -1
class EightPuzzle:
def init (self):
self._hval = 0
self._depth = 0
# parent node in search path
self._parent = None
self.adj_matrix = []
for i in range(3):
self.adj_matrix.append(_goal_state[i][:])
def eq (self, other):
if self. class != other. class :
return False
else:
for i in range(3):
p.adj_matrix[i] = self.adj_matrix[i][:]
return p
def _get_legal_moves(self):
"""Returns list of tuples with which the free space may
be swapped"""
free.append((row + 1, col))
if col < 2:
free.append((row, col + 1))
return free
def _generate_moves(self):
free = self._get_legal_moves()
zero = self.find(0)
p._depth = self._depth + 1
p._parent = self
return p
return map(lambda pair: swap_and_clone(zero, pair), free)
if self._parent ==
None: return path
else:
path.append(self)
return
self._parent._generate_solution_path(path)
closedl = []
move_count = 0
while len(openl) > 0:
x = openl.pop(0)
move_count += 1
if (is_solved(x)):
if len(closedl) > 0:
return x._generate_solution_path([]), move_count
else:
return [x]
succ = x._generate_moves()
idx_open = idx_closed = -1
for move in succ:
openl.append(move)
elif idx_open > -1:
copy = openl[idx_open]
if fval < copy._hval + copy._depth:
copy._hval = hval
copy._parent = move._parent
copy._depth = move._depth
elif idx_closed > -1:
copy = closedl[idx_closed]
if fval < copy._hval + copy._depth:
move._hval = hval
closedl.remove(copy)
openl.append(move)
closedl.append(x)
free = self._get_legal_moves()
target = random.choice(free)
self.swap((row, col), target)
row, col = target
def find(self, value):
return self.adj_matrix[row][col]
def poke(self, row, col, value):
temp = self.peek(*pos_a)
self.poke(pos_a[0], pos_a[1], self.peek(*pos_b))
self.poke(pos_b[0], pos_b[1], temp)
Heuristic template that provides the current and target position for each number and the
total function.
Parameters:
item_total_calc - takes 4 parameters: current row, target row, current col, target col.
Returns int.
total_calc - takes 1 parameter, the sum of item_total_calc over all entries, and returns int.
target_col = val % 3
target_row = val / 3
lambda t: math.sqrt(t))
def h_linear(puzzle):
return heur(puzzle,
lambda r, tr, c, tc: math.sqrt(math.sqrt((tr - r)**2 + (tc - c)**2)), lambda t:
t)
RESULT:
EX.NO:
8 QUEEN PROBLEM
DATE:
AIM:
ALGORITHM:
PROGRAM:
import copy
def take_input():
"""Accepts the size of the chess board""" while True:
try:
size = int(input('What is the size of the chessboard? n = \n')) if size == 1:
print("Trivial solution, choose a board size of atleast 4") if size <= 3:
print("Enter a value such that size>=4") continue
return size except ValueError:
print("Invalid value entered. Enter again") def get_board(size):
"""Returns an n by n board""" board = [0]*size
for ix in range(size): board[ix] = [0]*size
return board
def print_solutions(solutions, size):
"""Prints all the solutions in user friendly way""" for sol in solutions:
for row in sol: print(row)
print()
def is_safe(board, row, col, size):
"""Check if it's safe to place a queen at board[x][y]""" #check row on left side
for iy in range(col):
if board[row][iy] == 1: return False
ix, iy = row, col
while ix >= 0 and iy >= 0: if board[ix][iy] == 1:
return False ix-=1
iy-=1
jx, jy = row,col
while jx < size and jy >= 0: if board[jx][jy] == 1:
return False jx+=1
jy-=1 return True
def solve(board, col, size):
"""Use backtracking to find all solutions""" #base case
if col >= size: return
for i in range(size):
if is_safe(board, i, col, size): board[i][col] = 1
if col == size-1: add_solution(board) board[i][col] = 0 return
solve(board, col+1, size) #backtrack
board[i][col] = 0 def add_solution(board):
"""Saves the board state to the global variable 'solutions'""" global solutions
saved_board = copy.deepcopy(board) solutions.append(saved_board)
size = take_input() board = get_board(size) solutions = [] solve(board, 0, size)
print_solutions(solutions, size)
print("Total solutions = {}".format(len(solutions)))
OUTPUT:
RESULT:
EX.NO:
BREADTH FIRST SEARCH
DATE:
AIM:
ALGORITHM:
PROGRAM:
class Graph:
def init (self):
# dictionary containing keys that map to the corresponding vertex object self.vertices = {}
def add_vertex(self, key):
"""Add a vertex with the given key to the graph.""" vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
"""Return vertex object with the corresponding key.""" return self.vertices[key]
def contains (self, key): return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
"""Add edge from src_key to dest_key with given weight."""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def iter (self):
return iter(self.vertices.values())
class Vertex:
def init (self, key): self.key = key self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object.""" return self.key
def add_neighbour(self, dest, weight):
"""Make this vertex point to dest with given edge weight.""" self.points_to[dest] = weight
def get_neighbours(self):
"""Return all vertices pointed to by this vertex.""" return self.points_to.keys()
def get_weight(self, dest):
"""Get weight of edge from this vertex to dest.""" return self.points_to[dest]
def does_it_point_to(self, dest):
"""Return True if this vertex points to dest.""" return dest in self.points_to
class Queue:
def init (self): self.items = []
def is_empty(self): return self.items == []
def enqueue(self, data): self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def display_bfs(vertex):
"""Display BFS Traversal starting at vertex.""" visited = set()
q = Queue() q.enqueue(vertex)
visited.add(vertex) while not q.is_empty():
current = q.dequeue() print(current.get_key(), end=' ')
for dest in current.get_neighbours(): if dest not in visited:
visited.add(dest) q.enqueue(dest)
g = Graph() print('Menu')
print('add vertex <key>') print('add edge <src> <dest>') print('bfs <vertex key>') print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add': suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2]) if key not in g:
g.add_vertex(key) else:
print('Vertex already exists.') elif suboperation == 'edge':
src = int(do[2]) dest = int(do[3]) if src not in g:
print('Vertex {} does not exist.'.format(src)) elif dest not in g:
print('Vertex {} does not exist.'.format(dest)) else:
if not g.does_edge_exist(src, dest): g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'bfs': key = int(do[1])
print('Breadth-first Traversal: ', end='') vertex = g.get_vertex(key) display_bfs(vertex)
print()
elif operation == 'display': print('Vertices: ', end='') for v in g:
print(v.get_key(), end=' ') print()
print('Edges: ') for v in g:
for dest in v.get_neighbours(): w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))
print()
elif operation == 'quit':
break
OUTPUT:
RESULT:
EX.NO:
AIM:
ALGORITHM:
PROGRAM:
class Graph:
def init (self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
"""Add a vertex with the given key to the graph."""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
"""Return vertex object with the corresponding key."""
return self.vertices[key]
def contains (self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
"""Add edge from src_key to dest_key with given weight."""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def iter (self):
return iter(self.vertices.values())
class Vertex:
def init (self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key
def add_neighbour(self, dest, weight):
"""Make this vertex point to dest with given edge weight."""
self.points_to[dest] = weight
def get_neighbours(self):
"""Return all vertices pointed to by this vertex.""" return
self.points_to.keys()
def get_weight(self, dest):
"""Get weight of edge from this vertex to dest."""
return self.points_to[dest]
RESULT:
EX.NO:
TRAVELLING SALESMAN PROBLEM
DATE:
AIM:
ALGORITHM:
PROGRAM:
from sys import maxsize
V=4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s: vertex.append(i)
min_path = maxsize
while True:
current_pathweight = 0
k=s
for i in range(len(vertex)):
current_pathweight += graph[k][vertex[i]]
k = vertex[i]
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
if not next_permutation(vertex):
break
return min_path
def next_permutation(L):
n = len(L)
i=n-2
while i >= 0 and L[i] >= L[i + 1]:
i -= 1
if i == -1:
return False
j=i+1
while j < n and L[j] > L[i]:
j += 1 j -= 1
L[i], L[j] = L[j], L[i]
left = i + 1
right = n - 1
return True
if name == " main ":
OUTPUT:
RESULT:
EX.NO:
MIN-MAX ALGORITHM
DATE:
AIM:
ALGORITHM:
PROGRAM:
import math
def minimax (curDepth, nodeIndex, maxTurn, scores, targetDepth):
case : targetDepth reached
if (curDepth == targetDepth):
return scores[nodeIndex]
if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1,
False, scores, targetDepth))
else: return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1,
True, scores, targetDepth))
scores = [3, 5, 2, 9, 12, 5, 23, 23]
treeDepth = math.log(len(scores), 2)
print("The optimal value is : ", end = "")
print(minimax(0, 0, True, scores, treeDepth))
OUTPUT:
RESULT:
EX.NO:
FAMILY TREE
DATE:
AIM:
ALGORITHM:
PROGRAM:
parent(jayaramreddy,bhanuprasadreddy).
parent(jyothi,bhanuprasadreddy).
parent(bhanuprasadreddy,yamini).
male(jayaramreddy).
male(bhanuprasadreddy).
female(jyothi).
female(yamini).
mother(X,Y):-parent(X,Y),female(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X).
grandparent(X,Z):-parent(X,Y),parent(Y,Z).
OUTPUT:
RESULT:
EX.NO:
FACTORIAL
DATE:
AIM:
ALGORITHM:
PROGRAM:
fact(0, 1).
fact(N, F) :-
(% The below is for +ve factorialN > 0->
(N1 is N - 1,
fact(N1,F1),
F is N * F1);
% The below is for -ve factorial
N<0->(N1 is N+1,fact(N1, F1),F is N * F1)).
OUTPUT:
RESULT:
EX.NO: GCD OF TWO NUMBERS
DATE:
AIM:
ALGORITHM:
PROGRAM:
gcd(X,Y):-X=Y,write('GCD of two numbers is '),write(X);
X=0,write('GCD of two numbers is '),write(Y);
Y=0,write('GCD of two numbers is '),write(X);
Y>X,Y1 is Y-X,gcd(X,Y1);
X>Y,Y1 is X-Y,gcd(Y1,Y).
OUTPUT:
RESULT:
EX.NO:
INPUT FROM USER
DATE:
AIM:
ALGORITHM:
PROGRAM:
reference("yamini", "9493272585").
reference("radhika", "8919666297").
reference("hemanth", "9642499090").
reference("jayaram reddy", "9490013093").
OUTPUT:
RESULT:
EX.NO:
OUTPUT FROM USER
DATE:
AIM:
ALGORITHM:
PROGRAM:
type(ungulate,animal).
type(fish,animal).
is_a(zebra,ungulate).
is_a(herring,fish).
is_a(shark,fish).
lives(zebra,on_land).
lives(frog,on_land).
lives(frog,in_water).
lives(shark,in_water).
can_swim(Y):- type(X, animal), is_a(Y,X), lives(Y, in_water).
OUTPUT:
RESULT:
EX.NO: 12 MONKEY BANANA
DATE:
AIM:
ALGORITHM:
PROGRAM:
move(state(middle,onbox,middle,hasnot),
grasp,state(middle,onbox,middle,has)).
move(state(P,onfloor,P,hasnot),climb,
state(P,onbox,P,hasnot)).
move(state(P,onfloor,P,hasnot),push,
state(P1,onfloor,P1,hasnot)).
move(state(P1,onfloor,B,hasnot),walk,
state(P2,onfloor,B,hasnot)).
canget(state(_,_,_,has)) :-
write("get").
canget(State1) :-
move(State1,Move,State2),
canget(State2),
write(State2),nl.
OUTPUT:
RESULT:
EX.NO:
LIST
DATE:
AIM:
ALGORITHM:
PROGRAM:
11 A) PRINT LIST:
printlist([]).
printlist([X|List]) :-
write(X),nl,
printlist(List).
OUTPUT:
RESULT:
EX.NO: 13
MEDICAL DIAGNOSIS
DATE:
AIM:
ALGORITHM:
PROGRAM:
domains
disease,indication,name=symbol
predicates
hypothesis(name,disease)
symptom(name,indication)
clauses
symptom(yamini,fever).
symptom(yamini,rash) .
symptom(yamini,headache).
symptom(yamini,runn_nose).
symptom(hemanth,chills).
symptom(hemanth,fever).
symptom(hemnth,headache).
symptom(radhika,runny_nose).
symptom(radhika,rash).
symptom(radhika,flu).
hypothesis(Patient,measels):
symptom(Patient,fever),
symptom(Patient,cough),
symptom(Patient,conjunctivitis),
symptom(Patient,r ash).
hypothesis(Patient,german_measl es):
symptom(Patient,f ev er ),
symptom(Patient,headache),
symptom(Patient,runny_nose),
symptom(Patient,rash).
OUTPUT:
RESULT:
EX.NO:
DECISION TREE
DATE:
AIM:
ALGORITHM:
PROGRAM:
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
def importdata():
balance_data = pd.read_csv(
'https://archive.ics.uci.edu/ml/machine-learning-'+
'databases/balance-scale/balance-scale.data',
sep= ',', header = None)
print ("Dataset Length: ", len(balance_data))
print ("Dataset Shape: ", balance_data.shape)
print ("Dataset: ",balance_data.head())
return balance_data
def splitdataset(balance_data):
X = balance_data.values[:, 1:5]
Y = balance_data.values[:, 0]
X_train, X_test, y_train, y_test = train_test_split(
X, Y, test_size = 0.3, random_state = 100)
return X, Y, X_train, X_test, y_train, y_test
def train_using_gini(X_train, X_test, y_train):
clf_gini = DecisionTreeClassifier(criterion = "gini",
random_state = 100,max_depth=3, min_samples_leaf=5)
clf_gini.fit(X_train, y_train)
return clf_gini
def tarin_using_entropy(X_train, X_test, y_train):
clf_entropy = DecisionTreeClassifier(
criterion = "entropy", random_state = 100,
max_depth = 3, min_samples_leaf = 5)
clf_entropy.fit(X_train, y_train)
return clf_entropy
def prediction(X_test, clf_object):
y_pred = clf_object.predict(X_test)
print("Predicted values:")
print(y_pred)
return y_pred
def cal_accuracy(y_test, y_pred):
print("Confusion Matrix: ",
confusion_matrix(y_test, y_pred))
print ("Accuracy : ",
accuracy_score(y_test,y_pred)*100)
print("Report : ",
classification_report(y_test, y_pred))
# Driver code
def main():
# Building Phase
data = importdata()
X, Y, X_train, X_test, y_train, y_test = splitdataset(data)
clf_gini = train_using_gini(X_train, X_test, y_train)
clf_entropy = tarin_using_entropy(X_train, X_test, y_train)
# Operational Phase
print("Results Using Gini Index:")
# Prediction using gini
y_pred_gini = prediction(X_test, clf_gini)
cal_accuracy(y_test, y_pred_gini)
print("Results Using Entropy:")
# Prediction using entropy
y_pred_entropy = prediction(X_test, clf_entropy)
cal_accuracy(y_test, y_pred_entropy)
# Calling main function
if name ==" main ":
main()
OUTPUT:
ESULT:
EX.NO:
NEURAL NETWORK
DATE:
AIM:
ALGORITHM:
PROGRAM:
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
# Function importing Dataset
def importdata():
balance_data = pd.read_csv(
'https://archive.ics.uci.edu/ml/machine-learning-'+
'databases/balance-scale/balance-scale.data',
sep= ',', header = None)
# Printing the dataswet shape
print ("Dataset Length: ", len(balance_data))
print ("Dataset Shape: ", balance_data.shape)
# Printing the dataset obseravtions
print ("Dataset: ",balance_data.head())
return balance_data
# Function to split the dataset
def splitdataset(balance_data):
# Seperating the target variable
X = balance_data.values[:, 1:5]
Y = balance_data.values[:, 0]
# Spliting the dataset into train and test
X_train, X_test, y_train, y_test = train_test_split(
X, Y, test_size = 0.3, random_state = 100)
return X, Y, X_train, X_test, y_train, y_test
# Function to perform training with giniIndex.
def train_using_gini(X_train, X_test, y_train):
clf_gini = DecisionTreeClassifier(criterion = "gini",
random_state = 100,max_depth=3, min_samples_leaf=5)
# Performing training
clf_gini.fit(X_train, y_train)
return clf_gini
# Function to perform training with entropy.
def tarin_using_entropy(X_train, X_test, y_train):
# Decision tree with entropy
clf_entropy = DecisionTreeClassifier(
criterion = "entropy", random_state = 100,
max_depth = 3, min_samples_leaf = 5)
# Performing training
clf_entropy.fit(X_train, y_train)
return clf_entropy
# Function to make predictions
def prediction(X_test, clf_object):
# Predicton on test with giniIndex
y_pred = clf_object.predict(X_test)
print("Predicted values:")
print(y_pred)
return y_pred
# Function to calculate accuracy
def cal_accuracy(y_test, y_pred):
print("Confusion Matrix: ",
confusion_matrix(y_test, y_pred))
print ("Accuracy : ",
accuracy_score(y_test,y_pred)*100)
print("Report : ",
classification_report(y_test, y_pred))
# Driver code
def main():
data = importdata()
X, Y, X_train, X_test, y_train, y_test = splitdataset(data)
clf_gini = train_using_gini(X_train, X_test, y_train)
clf_entropy = tarin_using_entropy(X_train, X_test, y_train)
print("Results Using Gini Index:")
# Prediction using gini
y_pred_gini = prediction(X_test, clf_gini)
cal_accuracy(y_test, y_pred_gini)
print("Results Using Entropy:")
# Prediction using entropy
y_pred_entropy = prediction(X_test, clf_entropy)
cal_accuracy(y_test, y_pred_entropy)
# Calling main function
if name ==" main ":
main()
OUTPUT:
RESULT:
EX.NO:
SEO WEBPAGE USING WORDPRESS
DATE:
there are many website platforms that you can use when building a new site – Content Management
Systems (CMS) is what they’re usually called.
The idea of a CMS is to give you some easy-to-use tools so that you’re able to edit your site’s content
without any knowledge of coding. For the most part – from the user’s pointofview–thoseCMSlook
much like the familiar interfaces at Facebook or Google Docs. You basically create new pages or
documents,andthenhavethempublishedto the web.
• it’s opensource
• it’s free
• it’s the ultimate DIY solution for website building
• it’s extra versatile – can run any type of website
• it’s fast, optimized, and secure
• it’s SEO-ready – makes promotion easier
STEP 2: PICK A NAME FOR YOUR WEBSITE