0% found this document useful (0 votes)
8 views17 pages

Ai Programs (1-10)

The document contains multiple programming tasks, including implementations of various algorithms such as Breadth First Search, Depth First Search, A*, and others. Each task includes the code, expected output, and a brief description of the algorithm being implemented. The tasks cover a range of topics from graph traversal to puzzle solving and optimization problems.

Uploaded by

abhiraamuppari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Ai Programs (1-10)

The document contains multiple programming tasks, including implementations of various algorithms such as Breadth First Search, Depth First Search, A*, and others. Each task includes the code, expected output, and a brief description of the algorithm being implemented. The tasks cover a range of topics from graph traversal to puzzle solving and optimization problems.

Uploaded by

abhiraamuppari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1.

Write a Program to implement Breadth First Search


graph = {
'1':['2','3'],
'2':['4','5'],
'3':['6','7'],
'4':[],
'5':[],
'6':[],
'7':[]
}
visited = []
queue = []
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print(m,end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is BFS")
bfs(visited,graph,"2")

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

while len(open_set) > 0:

n = None

for v in open_set:

if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):

n=v

if n == stop_node or Graph_nodes[n] == None:

pass
else:

for (m, weight) in get_neighbors(n):

if m not in open_set and m not in closed_set:

open_set.add(m)

parents[m] = n

g[m] = g[n] + weight

else:

if g[m] > g[n] + weight:

g[m] = g[n] + weight

parents[m] = n

if m in closed_set:

closed_set.remove(m)

open_set.add(m)

if n == None:

print('Path does not exist!')

return None

if n == stop_node:

path = []

while parents[n] != n:

path.append(n)

n = parents[n]

path.append(start_node)

path.reverse()

print('Path found: {}'.format(path))

return path

open_set.remove(n)

closed_set.add(n)

print('Path does not exist!')

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 = {

'A': [('B', 2), ('E', 3)],

'B': [('C', 1),('G', 9)],

'C': None,

'E': [('D', 6)],

'D': [('G', 1)],

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 word in range(len(words)):

for i in range(len(words[word])):

ch = words[word][i]

Hash[ord(ch) - ord('A')] += pow(10, len(words[word]) - i - 1)

if mp[ord(ch) - ord('A')] == -1:

mp[ord(ch) - ord('A')] = 0

uniq += str(ch)

if i == 0 and len(words[word]) > 1:

CharAtfront[ord(ch) - ord('A')] = 1

for i in range(len(result)):

ch = result[i]

Hash[ord(ch) - ord('A')] -= pow(10, len(result) - i - 1)

if mp[ord(ch) - ord('A')] == -1:

mp[ord(ch) - ord('A')] = 0

uniq += str(ch)

if i == 0 and len(result) > 1:

CharAtfront[ord(ch) - ord('A')] = 1

mp = [-1]*(26)

return True

def solve(words, i, S, mp, used, Hash, CharAtfront):

if i == len(words):

return S == 0

ch = words[i]

val = mp[ord(words[i]) - ord('A')]

if val != -1:

return solve(words, i + 1, S + val * Hash[ord(ch) - ord('A')], mp, used, Hash, CharAtfront)

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

x |= solve(words, i + 1, S + l * Hash[ord(ch) - ord('A')], mp, used, Hash, CharAtfront)

mp[ord(ch) - ord('A')] = -1

used[l] = 0

return x

arr = [ "SIX", "SEVEN", "SEVEN" ]

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):

points = list(range(0, len(matrix)))

solution = []

for i in range(0, len(matrix)):

random_point = points[random.randint(0, len(points) - 1)]

solution.append(random_point)

points.remove(random_point)

return solution

def path_length(matrix, solution):

cycle_length = 0

for i in range(0, len(solution)):

cycle_length += matrix[solution[i]][solution[i - 1]]

return cycle_length

def neighbors(matrix, solution):

neighbors = []

for i in range(len(solution)):

for j in range(i + 1, len(solution)):

neighbor = solution.copy()

neighbor[i] = solution[j]

neighbor[j] = solution[i]

neighbors.append(neighbor)

best_neighbor = neighbors[0]

best_path = path_length(matrix, best_neighbor)

for neighbor in neighbors:

current_path = path_length(matrix, neighbor)

if current_path < best_path:

best_path = current_path

best_neighbor = neighbor

return best_neighbor, best_path


def hill_climbing(coordinate):

matrix = generate_matrix(coordinate)

current_solution = solution(matrix)

current_path = path_length(matrix, current_solution)

neighbor = neighbors(matrix,current_solution)[0]

best_neighbor, best_neighbor_path = neighbors(matrix, neighbor)

while best_neighbor_path < current_path:

current_solution = best_neighbor

current_path = best_neighbor_path

neighbor = neighbors(matrix, current_solution)[0]

best_neighbor, best_neighbor_path = neighbors(matrix, neighbor)

return current_path, current_solution

final_solution = hill_climbing(coordinate)

print("The solution is \n", final_solution[1])

Output:

6.8-PUZZLE:
import copy

from heapq import heappush, heappop

n=3

row = [ 1, 0, -1, 0 ]

col = [ 0, -1, 0, 1 ]

class priorityQueue:

def _init_(self):
self.heap = []

def push(self, k):

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:

def _init_(self, parent, mat, empty_tile_pos,

cost, level):

self.parent = parent

self.mat = mat

self.empty_tile_pos = empty_tile_pos

self.cost = cost

self.level = level

def _lt_(self, nxt):

return self.cost < nxt.cost

def calculateCost(mat, final) -> int:

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

def newNode(mat, empty_tile_pos, new_empty_tile_pos,

level, parent, final) -> node:

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]

new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]

cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,

cost, level)

return new_node

def printMatrix(mat):

for i in range(n):

for j in range(n):

print("%d " % (mat[i][j]), end = " ")

print()

def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

def printPath(root):

if root == None:

return

printPath(root.parent)

printMatrix(root.mat)

print()

def solve(initial, empty_tile_pos, final):

pq = priorityQueue()

cost = calculateCost(initial, final)

root = node(None, initial,empty_tile_pos, cost, 0)

pq.push(root)

while not pq.empty():

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 ]

solve(initial, empty_tile_pos, final)

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 (board[i][j],end=' ')

print()

def isSafe(board, row, col):

for i in range(col):

if board[row][i] == 1:

return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j] == 1:

return False

for i, j in zip(range(row, N, 1), range(col, -1, -1)):

if board[i][j] == 1:

return False

return True

def solveNQUtil(board, col):

if col >= N:

return True

for i in range(N):

if isSafe(board, i, col):
board[i][col] = 1

if solveNQUtil(board, col + 1) == True:

return True

board[i][col] = 0

return False

def solveNQ():

board = [ [0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0]

if solveNQUtil(board, 0) == False:

print ("Solution does not exist")

return False

printSolution(board)

return True

solveNQ()

Output:

enter the no.of queens: 8


10000000
00000010
00001000
00000001
01000000
00010000
00000100
00100000

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

from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot=ChatBot('corona bot')

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train("chatterbot.corpus.english.greetings",

"chatterbot.corpus.english.conversations" )

response = chatbot.get_response('What is your Number')

print(response)

response = chatbot.get_response('Who are you?')


print(response)

Output:

10.WATERJUG:
from collections import defaultdict

jug1, jug2, aim = 4, 3, 2

visited = defaultdict(lambda: False)

def waterJugSolver(amt1, amt2):

if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):

print(amt1, amt2)

return True

if visited[(amt1, amt2)] == False:

print(amt1, amt2)

visited[(amt1, amt2)] = True

return (waterJugSolver(0, amt2) or

waterJugSolver(amt1, 0) or

waterJugSolver(jug1, amt2) or

waterJugSolver(amt1, jug2) or

waterJugSolver(amt1 + min(amt2, (jug1-amt1)),

amt2 - min(amt2, (jug1-amt1))) or

waterJugSolver(amt1 - min(amt1, (jug2-amt2)),

amt2 + min(amt1, (jug2-amt2))))

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:

Enter the number of disks: 3


Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.
Move disk 2 from rod B to rod C. Move disk 1 from rod A to rod C.d A to rod C.
12.Travelling Sales person:
from sys import maxsize
from itertools import permutations

v=4

def travellingSalesmanProblem(graph, s):

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]

min_path = min(min_path, current_pathweight)

return min_path

if __name__ == "__main__":

graph = [[0, 10, 15, 20], [10, 0, 35, 25],

[15, 35, 0, 30], [20, 25, 30, 0]]

s=0

print(travellingSalesmanProblem(graph, s))

Output:

80

You might also like