Professional Documents
Culture Documents
Ai Merged PDF
Ai Merged PDF
Date :
TOY PROBLEM
Problem Statement : Given an integer N and an array of seats[] where N is the number of people
standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the i th row of
the movie theater. The task is to find the maximum amount a theater owner can make by selling
movie tickets to N people. Price of a ticket is equal to the maximum number of empty seats among
all the rows.
Algorithm:
Optimization technique: This problem can be solved by using a priority queue that will store the
count of empty seats for every row and the maximum among them will be available at the top.
1. Create an empty priority_queue q and traverse the seats[] array and insert all elements
into the priority_queue.
2. Initialize two integer variable ticketSold = 0 and ans = 0 that will store the number of
tickets sold and the total collection of the amount so far.
3. Now check while ticketSold < N and q.top() > 0 then remove the top element from the
priority_queue and update ans by adding top element of the priority queue. Also store this
top value in a variable temp and insert temp – 1 back to the priority_queue.
4. Repeat these steps until all the people have been sold the tickets and print the final result.
Result: Successfully found out the maximum amount the theater owner can make by selling
movie tickets to N people for a movie.
5
Exercise: 2
Date :
GRAPH COLORING PROBLEM
PROBLEM STATEMENT : Given a graph, color its edges such that no two adjacent have
the same color using minimum number of colors and return the Chromatic number.
ALGORITHM :
Initialize:
1. Consider the currently picked vertex and color it with the lowest numbered color that has
2. If all previously used colors appear on vertices adjacent to v, assign a new color to it.
OPTIMIZATION TECHNIQUE:
Graph coloring problem is to assign colors to certain elements of a graph subject to certain
constraints.
Vertex coloring is the most common graph coloring problem. The problem is, given m colors,
find a way of coloring the vertices of a graph such that no two adjacent vertices are colored using
1
the same color. The other graph coloring problems like Edge Coloring (No vertex is incident to
two edges of same color) and Face Coloring (Geographical Map Coloring) can be transformed
Chromatic Number: The smallest number of colors needed to color a graph G is called its
chromatic number. For example, the following can be colored at least 2 colors.
import networkx as nx
import numpy as np
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5])
nodes = list(G.nodes)
edges = list(G.edges)
2
color_lists = []
color_of_edge = []
some_colors = ['red','green','blue','yellow']
color_lists.append([])
color_of_edge.append(-1)
def getSmallestColor(ls1,ls2):
i=1
i=i+1
return i
i=0
for ed in edges:
newColor = getSmallestColor(color_lists[ed[0]],color_lists[ed[1]])
color_lists[ed[0]].append(newColor)
color_lists[ed[1]].append(newColor)
color_of_edge[i] = newColor
i=i+1
3
# Makin graph again
G = nx.Graph()
for i in range(len(edges)):
G.add_edge(edges[i][0],edges[i][1],color=some_colors[color_of_edge[i]-1])
colors = nx.get_edge_attributes(G,'color').values()
plt.show()
OUTPUT :
4
CODE - VERTEX COLORING :
import networkx as nx
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5])
node_colors = []
node_colors.append(colors[d[i]])
plt.show()
5
OUTPUT :
import networkx as nx
G = nx.Graph()
G.add_nodes_from([1,2,3,4,5])
nodes = list(G.nodes)
edges = list(G.edges)
some_colors = ['red','green','blue','yellow']
no_of_faces = len(edges)+2-len(nodes)-1
6
def regionColour(regions):
for i in range(1,regions+1):
print("FACE 1 : "+some_colors[i%4])
regionColour(no_of_faces)
OUTPUT :
RESULT :
Edge, vertex and face coloring problem which are together known as graph coloring problem
solved and visualized in an optimized way using greedy approach.
7
Experiment No. 4a - Implementation of Breadth First Search
Aim
To implement BFS in Python.
ALGORITHM
Algorithm:
1. Create a queue
2. Mark each new node as visited and put that node into the queue
3. While Queue is non-empty:
4. Remove the head of Queue
5. Mark and enqueue all (unvisited) neighbors.
Program
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited_bfs = []
queue = []
def bfs(visited_bfs, graph, node):
visited_bfs.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
visited = set()
print("BFS:" , end =" ")
bfs(visited_bfs, graph, 'A')
Results
Breadth First Search was successfully implemented in Python.
Experiment No. 4b - Implementation of Depth First Search
Aim
To implement DFS in Python.
ALGORITHM
The DFS algorithm works as follows:
visited_bfs = []
queue = []
visited = set()
Results
Depth First Search was successfully implemented in Python.
NAME:
REG.NO:
EXPERIMENT 5 – DEVELOPING BEST FIRST SEARCH AND A* ALGORITHM FOR
REAL WORLD PROBLEMS
AIM
To write a python program for developing best first search and a* algorithm for real world problems.
ALGORITHM
1.First, create a list of all the characters that need assigning to pass to Solve.
2.If all characters are assigned, return true if puzzle is solved, false otherwise.
3.Otherwise, consider the first unassigned character for (every possible choice among the digits
not in use)make that choice and then recursively try to assign the rest of the characters.
4.If all digits have been tried and nothing worked, return false to trigger backtracking.
PROGRAM
import time
import itertools
def timeit(fn):
def wrapper():
start = time.perf_counter()
ret = fn()
elapsed = time.perf_counter() - start
print("%s took %2.fs" % (fn.__name__, elapsed))
return ret
return wrapper
@timeit
def solve1():
for s in range(1,10):
for e in range(0,10):
for n in range(0,10):
for d in range(0,10):
for m in range(1,10):
for o in range(0,10):
for r in range(0,10):
for y in range(0,10):
if distinct(s,e,n,d,m,o,r,y):
send = 1000*s + 100*e + 10*n + d
more = 1000*m + 100*o + 10*r + e
money = 10000*m + 1000*o + 100*n + 10*e + y
if send + more == money:
return send, more, money
def distinct(*args):
return len(set(args)) == len(args)
@timeit
def solve2():
letters = ('s','e','n','d','m','o','r','y')
digits = range(10)
for perm in itertools.permutations(digits, len(letters)):
sol = dict(zip(letters, perm))
if sol['s'] == 0 or sol['m'] == 0:
continue
send = 1000*sol['s'] + 100*sol['e'] + 10*sol['n'] + sol['d']
more = 1000*sol['m'] + 100*sol['o'] + 10*sol['r'] + sol['e']
money = 10000*sol['m'] + 1000*sol['o'] + 100*sol['n'] + 10*sol['e'] + sol['y']
if send + more == money:
return send, more, money
print(solve1())
print(solve2())
OUTPUT
RESULT
Thus, developing best first search and a* algorithm for real world problems has been done
successfully.
NAME:
REG.NO:
EXPERIMENT 6 – IMPLEMENTATION OF MINIMAX ALGORITHM FOR AN
APPLICATION
AIM
To write a python program for implementation of minimax algorithm for an application.
ALGORITHM
1.Start.
2.Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice between 3
and 5. Being the minimizer it will definitely choose the least among both, that is 3.
3.Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice between 2
and 9. He will choose 2 as it is the least among the two values.
4. Being the maximizer you would choose the larger value that is 3. Hence the optimal move for
the maximizer is to go LEFT and the optimal value is 3.
PROGRAM
import math
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, 21]
treeDepth = math.log(len(scores), 2)
RESULT
Thus, implementation of minimax algorithm for an application has been done successfully.
NAME:
REG. NO:
Aim:
To implement unification with Python.
Algorithm:
b, Else if Ψ1 is a variable:
c, Else if Ψ2 is a variable:
Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.
a, Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the result
into S.
b, If S = False then returns False
Program:
def get_index_comma(string):
"""
"""
index_list = list()
par_count = 0
for i in range(len(string)):
index_list.append(i)
par_count += 1
par_count -= 1
return index_list
def is_variable(expr):
"""
"""
for i in expr:
if i == '(':
return False
return True
def process_expression(expr):
"""
input: - expression:
Q
- list of arguments
"""
index = None
for i in range(len(expr)):
if expr[i] == '(':
index = i
break
predicate_symbol = expr[:index]
# Remove '(' in the first index and ')' in the last index
expr = expr[1:len(expr) - 1]
# List of arguments
arg_list = list()
indices = get_index_comma(expr)
if len(indices) == 0:
arg_list.append(expr)
else:
arg_list.append(expr[:indices[0]])
arg_list.append(expr[i + 1:j])
arg_list.append(expr[indices[len(indices) - 1] + 1:])
def get_arg_list(expr):
"""
input: expression:
_, arg_list = process_expression(expr)
flag = True
while flag:
flag = False
for i in arg_list:
if not is_variable(i):
flag = True
_, tmp = process_expression(i)
for j in tmp:
if j not in arg_list:
arg_list.append(j)
arg_list.remove(i)
return arg_list
"""
Check if var occurs in expr
"""
arg_list = get_arg_list(expr)
if var in arg_list:
return True
return False
# Step 1:
if expr1 == expr2:
return 'Null'
else:
return False
if check_occurs(expr1, expr2):
return False
else:
tmp = str(expr2) + '/' + str(expr1)
return tmp
if check_occurs(expr2, expr1):
return False
else:
return tmp
else:
# Step 2
if predicate_symbol_1 != predicate_symbol_2:
return False
# Step 3
return False
else:
sub_list = list()
# Step 5:
for i in range(len(arg_list_1)):
if not tmp:
return False
pass
else:
if type(tmp) == list:
for j in tmp:
sub_list.append(j)
else:
sub_list.append(tmp)
# Step 6
return sub_list
if __name__ == '__main__':
# Data 1
f1 = 'p(b(A), X, f(g(Z)))'
f2 = 'p(Z, f(Y), f(Y))'
# Data 2
# Data 3
if not result:
print('Unification failed!')
else:
print('Unification successfully!')
print(result)
Output:
Result:
Aim:
To solve sudoku using knowledge representation.
Algorithm:
1. Start.
2. Find some empty space.
3. Attempt to place the digits 1-9 in that space.
4. Check if that digit is valid in the current spot based on the current board.
5. a. If the digit is valid, recursively attempt to fill the board using steps 1-3.
b. If it is not valid, reset the square you just filled and go back to the previous step.
6. Once the board is full by the definition of this algorithm we have found a solution.
7. Stop.
Program:
size = 9
matrix = [
[5,0,0,0,7,0,0,0,0],
[0,0,0,1,9,0,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,0]]
def print_sudoku():
for i in matrix:
print (i)
num_unassign = 0
for i in range(0,size):
if matrix[i][j] == 0:
row = i
col = j
num_unassign = 1
return a
return a
for i in range(0,size):
if matrix[r][i] == n:
return False
for i in range(0,size):
if matrix[i][c] == n:
return False
row_start = (r//3)*3
col_start = (c//3)*3;
for i in range(row_start,row_start+3):
for j in range(col_start,col_start+3):
if matrix[i][j]==n:
return False
return True
def solve_sudoku():
row = 0
col = 0
a = number_unassigned(row, col)
if a[2] == 0:
return True
row = a[0]
col = a[1]
for i in range(1,10):
matrix[row][col] = i
if solve_sudoku():
return True
matrix[row][col]=0
return False
if solve_sudoku():
print_sudoku()
else:
print("No solution")
Output:
Result:
Algorithm:
1. Import the necessary header files.
Program:
"""n = int(input("enter number of stacks"))
stac = []
for i in range(n):
stac.append(temp)"""
stac = [['B','A'],['D'],['C']]
finalstac = ['B','C','A','D']
nu = 4
intermediate = []
for i in range(len(st)):
for j in range(len(st[i])):
if(st[i][j]==arg):
return(i,j)
for i in stac:
for j in i:
j = list(j)
intermediate.append(j)
t = finalstac[i]
if(i==0):
flagm,flagn = matrixIndex(intermediate,t)
continue
else:
intermediate[flagm].append(t)
indm,indn = matrixIndex(intermediate,t)
intermediate[indn][indm]=" "
Output:
Result: Thus Block World Problem has been successfully implemented.
NAME:
REG. NO:
Aim:
To implement uncertain methods for an application.
Algorithm:
1. Start
2. import all required libraries required.
3. Do data cleaning if required.
4. To understand the data, use visualization and find patterns.
5. Split the dataset for training and testing.
6. Finally predict the accuracy.
7. Stop.
Program:
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):
n = np.size(x)
m_x = np.mean(x)
m_y = np.mean(y)
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return (b_0, b_1)
def main():
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0], b[1]))
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
Output:
Result:
ALGORITHM
PROGRAM
iris = datasets.load_iris()
X = iris.data
y = iris.target
abc = AdaBoostClassifier(n_estimators=50,
learning_rate=1)
model = abc.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
svc=SVC(probability=True, kernel='linear')
y_pred = model.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
OUTPUT
RESULT
Thus, development of ensemble model for any application has been implemented successfully.
NAME:
REG. NO:
Aim:
To build the classification model using the gradient boosting algorithm.
Algorithm:
1. Start.
2. Creating a First Base Learner.
3. Calculating the Total Error (TE).
4. Calculating Performance of Stump.
5. Updating Weights.
6. Creating A New Dataset.
7. Stop.
Program:
## defining dataset
X, y = make_classification(n_samples=1000, n_features=20,
print(X.shape, y.shape)
## defining dataset
model = GradientBoostingClassifier()
## define dataset
n_redundant=5, random_state=7)
model = GradientBoostingClassifier()
-2.82646737, 0.44916808]
yhat = model.predict([row])
## summarize prediction
Output:
Result:
AIM: To write a python program for tokenizing a given text, extracting usernames from
emails, spelling corrections in a given text, extracting all the pronouns in a text and removal
of punctuations from the text using artificial intelligence methods.
nltk.download('punkt')
nltk.download('stop')
nltk.download('stopwords')
text="It has been proved by statistics, that if everyone wears a mask o
utside home,dreaded ‘second wave’ of the pandemic can be avoided."
tokens=nltk.word_tokenize(text)
for token in tokens:
print(token)
OUTPUT:
ALGORITHM: (extracting usernames from emails)
1) get the input string from user
4) if the string satisfies the condition of regular expression, then the email id is valid.
OUTPUT:
3. Use your domain specific dataset to build a better corpus for your data .
OUTPUT:
OUTPUT:
ALGORITHM: (and removal of punctuations)
1. To facility the spell check, corpus is needed.
" ".join(new_tokens)
OUTPUT:
Aim:
To Apply Deep learning methods for an application.
Algorithm:
1. Start
2. Load the data
3. Examine the data
4. One-hot encode the output
5. Build the model architecture
6. Train the model
7. Evaluate the model
8. Stop.
Program:
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42)
print(x_train.shape)
print(x_test.shape)
print(x_train[0])
print(y_train[0])
# One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])
Output:
Result: