AI LAB OUTPUT - Colaboratory
AI LAB OUTPUT - Colaboratory
# N Queen Problem
print ("Enter the number of queens")
N = int(input())
# here we create a chessboard
# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
#N-Queen Problem
N = 8 # (size of the chessboard)
[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0],
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 1/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []
# Node structure
class node:
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
t t
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 2/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
return count
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 3/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Generate all possible children
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]):
# Driver Code
# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
output 1
5
2
6
3
0
7 8 4
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 7 4
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 4/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Python3 program to find the next optimal move for a player
player, opponent = 'x', 'o'
for i in range(3) :
for j in range(3) :
if (board[i][j] == '_') :
return True
return False
if (b[0][col] == player) :
return 10
elif (b[0][col] == opponent) :
return -10
if (b[0][0] == player) :
return 10
elif (b[0][0] == opponent) :
return -10
if (b[0][2] == player) :
return 10
elif (b[0][2] == opponent) :
return -10
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 5/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 6/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# This will return the best possible move for the player
def findBestMove(board) :
bestVal = -1000
bestMove = (-1, -1)
bestMove = findBestMove(board)
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 7/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
if maximizingPlayer:
best = MIN
return best
else:
best = MAX
return best
# Driver Code
if __name__ == "__main__":
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 8/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#SUDOKU SOLVER
# N is the size of the 2D matrix N*N
N = 9
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 9/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
grid[row][col] = num
# Driver Code
if (solveSudoku(grid, 0, 0)):
printing(grid)
else:
print("no solution exists ")
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 10/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#Wumpus Game Using PropositionalModel Checking Algorithm
import random
class WumpusGame(object):
# Create arbitrary caves from a list of edges (see the end of the script for example).
if edges:
cave = {}
N = max([edges[i][0] for i in range(len(edges))])
for i in range(N):
exits = [edge[1] for edge in edges if edge[0] == i]
cave[i] = exits
self.cave = cave
self.threats = {}
self.arrows = 5
"""
HELPER: These methods wrap processes that are useful or called often.
"""
def get_safe_rooms(self):
""" Returns a list containing all numbers of rooms that
do not contain any threats
"""
return list(set(self.cave.keys()).difference(self.threats.keys()))
def populate_cave(self):
""" Drop player and threats into random rooms in the cave.
"""
for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']:
pos = random.choice(self.get_safe_rooms())
self.threats[pos] = threat
self.player_pos = random.choice(self.get_safe_rooms())
BFS works like this: start with the source vertex, maybe it is already the target?
If not, then go a level deeper and find out, if one of the children (also called
successors) of the source vertex is the wanted target. If not, then for each child,
go a level deeper and find out if one of the grand-children is the wanted target.
If not, then for each grand-child go a level deeper and so on.
The following is a recursive implementation of BFS. You will not find any loops
(for, while). Instead you manage two lists. The first one ('stack') contains all
the vertices of the current depth-level (e.g. all grand children). The second
('visited') contains all vertices that you already checked. Now there are three
possibilites: Either stack is empty, then all vertices have been checked unsuccessfully;
or the target vertex is a member of the stack, then you are happy; or the target is
not a member of the stack, but there are still some vertices that you did not visit,
then you append to the stack, all successors of the members of the stack and the old
stack now belongs to the visited vertices.
"""
# Set up some initial values.
graph = self.cave
depth = 0
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 11/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 12/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
def search(stack, visited, target, depth):
if stack == []: # The whole graph was searched, but target was not found.
return False, -1
if target in stack:
return True, depth
visited = visited + stack
stack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited))
depth += 1
if depth > max_depth: # Target is too far away from the source.
return False, depth
else: # Visit all successors of vertices in the stack.
return search(stack, visited, target, depth)
"""
INPUT / OUTPUT: The player interacts with the game.
"""
def get_players_input(self):
""" Queries input until valid input is given.
"""
while 1: # Query the action.
if mode == 'm':
try: # When walking, the target must be adjacent to the current room.
assert target in self.cave[self.player_pos]
break
except AssertionError:
print("You cannot walk that far. Please use one of the tunnels.")
"""
CORE / GAME LOGIC
"""
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 13/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 14/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Only if nothing else happens, the player enters the room of his choice.
return room_number
# If this was your last arrow and it did not hit the wumpus...
if self.arrows < 1: # This (or the updating of self.arrows) seems to be broken...
print("Your quiver is empty.")
return -1
# If you shoot into another room, the Wumpus has a 75% of chance of waking up and moving into an adjacent room.
if random.random() < 0.75:
#print("DEBUG: Wumpus moved.")
for room_number, threat in self.threats.items():
if threat == 'wumpus':
wumpus_pos = room_number
new_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys())))
del self.threats[room_number]
self.threats[new_pos] = 'wumpus'
if new_pos == self.player_pos: # Wumpus entered players room.
print("Wumpus enters your room and eats you!")
return -1
return self.player_pos
def gameloop(self):
while 1:
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 15/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
print()
print("Game over!")
if __name__ == '__main__':
# Only executed if you start this script as the main script,
# i.e. you enter 'python path/to/wumpus.py' in a terminal.
# Assuming you saved the script in the directory 'path/to'
# and named it 'wumpus.py'.
# TODO: In the original game you can replay a dungeon (same positions of you and the threats)
WG = WumpusGame()
WG.gameloop()
Game over!
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 16/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#Create Naïve Bayes Models
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from pandas import DataFrame
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
# The dataset
iris = datasets.load_iris()
X = iris.data
Y = iris.target
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=1/3)
# Training a Gaussian Naive Bayes classifier
model = GaussianNB()
model.fit(X_train, Y_train)
# Predictions
model_predictions = model.predict(X_test)
print("\n",model_predictions)
print("\n",Y_test)
# Accuracy of prediction
accuracyScore = accuracy_score(Y_test, model_predictions)
print("\naccuracyScore is",accuracyScore )
# Creating a confusion matrix
cm=confusion_matrix(Y_test,model_predictions)
print("\nconfusion matrix",cm)
#implementing Naive Baysian algorithm
# Importing library
import [0
math
0 2 2 1 0 2 1 1 1 0 1 1 2 2 2 2 1 1 0 1 2 1 0 1 0 2 1 2 1 0 0 2 0 2 1 0
import 2random
0 0 2 2 1 1 2 1 0 0 0 2]
import csv
[0 0 2 2 1 0 2 1 1 1 0 1 1 1 2 1 2 1 1 0 1 2 1 0 1 0 2 1 2 1 0 0 2 0 1 1 0
2 0 0 2 2 1 1 2 1 0 0 0 2]
# the categorical class names are changed to numberic data
# eg: accuracyScore is 0.94
yes and no encoded to 1 and 0
def encode_class(mydata):
confusion matrix [[16 0 0]
classes = []
[ 0 17 3]
for[ i
0 in
0 range(len(mydata)):
14]]
if mydata[i][-1] not in classes:
classes.append(mydata[i][-1])
for i in range(len(classes)):
for j in range(len(mydata)):
if mydata[j][-1] == classes[i]:
mydata[j][-1] = i
return mydata
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 17/17