Ai Programs (1-10)
Ai Programs (1-10)
output:
Following is BFS
1234567
2.Write a Program to implement Depth First Search
graph = {
'1':['2','3'],
'2':['4','5'],
'3':['6','7'],
'4':[],
'5':[],
'6':[],
'7':[]
}
visited = set()
def dfs(visited,graph,node):
if node not in visited:
visited.add(node)
print(node,end = " ")
for neighbour in graph[node]:
dfs(visited,graph,neighbour)
print("Following is the DFS")
dfs(visited,graph,'1')
Output:
Following is the DFS
1245367
3.A*
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
n = None
for v in open_set:
n=v
pass
else:
open_set.add(m)
parents[m] = n
else:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
return H_dist[n]
Graph_nodes = {
'C': None,
aStarAlgo('A', 'G')
Output:
Path found:[‘A’,’E’,’D’,’G’]
4.CRYPT:
def isSolvable(words, result):
mp = [-1]*(26)
used = [0]*(10)
Hash = [0]*(26)
CharAtfront = [0]*(26)
uniq = ""
for i in range(len(words[word])):
ch = words[word][i]
mp[ord(ch) - ord('A')] = 0
uniq += str(ch)
CharAtfront[ord(ch) - ord('A')] = 1
for i in range(len(result)):
ch = result[i]
mp[ord(ch) - ord('A')] = 0
uniq += str(ch)
CharAtfront[ord(ch) - ord('A')] = 1
mp = [-1]*(26)
return True
if i == len(words):
return S == 0
ch = words[i]
if val != -1:
x = False
for l in range(10):
if CharAtfront[ord(ch) - ord('A')] == 1 and l == 0:
continue
if used[l] == 1:
continue
mp[ord(ch) - ord('A')] = l
used[l] = 1
mp[ord(ch) - ord('A')] = -1
used[l] = 0
return x
S = "TWENTY"
if isSolvable(arr, S):
print("Yes")
else:
print("No")
Output:
5.HILL CLIMLBING:
import random
import numpy as np
import networkx as nx
coordinate = np.array([[1,2], [30,21], [56,23], [8,18], [20,50], [3,4], [11,6], [6,7], [15,20], [10,9],
[12,12]])
def generate_matrix(coordinate):
matrix = []
for i in range(len(coordinate)):
for j in range(len(coordinate)) :
p = np.linalg.norm(coordinate[i] - coordinate[j])
matrix.append(p)
matrix = np.reshape(matrix, (len(coordinate),len(coordinate)))
return matrix
def solution(matrix):
solution = []
solution.append(random_point)
points.remove(random_point)
return solution
cycle_length = 0
return cycle_length
neighbors = []
for i in range(len(solution)):
neighbor = solution.copy()
neighbor[i] = solution[j]
neighbor[j] = solution[i]
neighbors.append(neighbor)
best_neighbor = neighbors[0]
best_path = current_path
best_neighbor = neighbor
matrix = generate_matrix(coordinate)
current_solution = solution(matrix)
neighbor = neighbors(matrix,current_solution)[0]
current_solution = best_neighbor
current_path = best_neighbor_path
final_solution = hill_climbing(coordinate)
Output:
6.8-PUZZLE:
import copy
n=3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
def _init_(self):
self.heap = []
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:
return False
class node:
cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
cost, level)
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print()
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
pq = priorityQueue()
pq.push(root)
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]
if isSafe(new_tile_pos[0], new_tile_pos[1]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
Output:
123
560
784
123
506
784
123
586
704
123
586
074
7.N-QUEENS:
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print()
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
return True
board[i][col] = 0
return False
def solveNQ():
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
if solveNQUtil(board, 0) == False:
return False
printSolution(board)
return True
solveNQ()
Output:
8.Blocks World:
n = int(input("Entet the no.of blocks"))
a = list(map(str,input().split(",")))
b = list(map(str,input().split(",")))
l = len(a)
l2 = len(b)
print(a)
print(b)
i =0
while(i<l):
if(a[i] == b[i]):
i+=1
continue
else:
break
i+=1
if(i==l-1):
print("All blocks are placed in order")
j = l-1
while(j>=i):
if(j==0):
j-=1
continue
print("place ",a[j]," on table ")
j-=1
while(i<l):
if(i==0):
i+=1
continue
print("place ",b[i]," on ",b[i-1])
i+=1
Output 1:
Entet the no.of blocks4
a,b,c,d
a,b,d,c
['a', 'b', 'c', 'd']
['a', 'b', 'd', 'c']
place d on table
place c on table
place d on b
place c on d
9.CHATBOT:
from chatterbot import ChatBot
chatbot=ChatBot('corona bot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.corpus.english.greetings",
"chatterbot.corpus.english.conversations" )
print(response)
Output:
10.WATERJUG:
from collections import defaultdict
print(amt1, amt2)
return True
print(amt1, amt2)
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
else:
return False
print("Steps: ")
waterJugSolver(0, 0)2
Output:
Steps:
0 ,0
0 ,3
3,0
3,3
4,2
0,2
11.Towers of Hanoi:
def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target)
)
return
# function call itself
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, t
arget))
tower_of_hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter the number of disks: '))
tower_of_hanoi(disks,’A,’B,’C’)
Output:
v=4
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
return min_path
if __name__ == "__main__":
s=0
print(travellingSalesmanProblem(graph, s))
Output:
80