AD3311 Lab Program
AD3311 Lab Program
Program:
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
board_dict[flatten] = 0
return self.get_paths(board_dict)
if len(current_nodes) == 0:
return -1
results = []
pos_0 = node.index(0)
return results
# 8-Queens Solver
def attack(i, j, board):
board[i][j] = 1
if eight_queens(n - 1, board):
return True
board[i][j] = 0
return False
# Cryptarithmetic Solver
def find_value(word, assigned):
num = 0
for char in word:
num = num * 10
num += assigned[char]
return num
cur_letter = letters.pop()
for num in range(10):
if num not in assigned.values():
assigned[cur_letter] = num
_solve(word1, word2, result, letters, assigned, solutions)
assigned.pop(cur_letter)
letters.append(cur_letter)
if solutions:
print('\nSolutions:')
for soln in solutions:
print(f'{soln[0]}\t{soln[1]}')
else:
print('0 Solutions!')
# Main Program
if __name__ == '__main__':
print("Select a problem to solve:")
print("1. 8-Puzzle Problem")
print("2. 8-Queens Problem")
print("3. Cryptarithmetic Puzzle")
if choice == 1:
# 8-puzzle problem
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
ob = PuzzleSolution()
print("NO OF MOVES==", ob.solve(matrix))
elif choice == 2:
# 8-Queens Problem
N = 8 # Fixed to 8-Queens
board = [[0] * N for _ in range(N)]
eight_queens(N, board)
print("Solution for 8-Queens Problem:")
for row in board:
print(row)
elif choice == 3:
# Cryptarithmetic Puzzle
word1 = input("Enter WORD1: ").upper()
word2 = input("Enter WORD2: ").upper()
result = input("Enter RESULT: ").upper()
if not word1.isalpha() or not word2.isalpha() or not result.isalpha():
raise TypeError("Inputs should only consist of alphabets.")
OUTPUT:
8-Puzzle Problem:
NO OF MOVES== 4
8-Queens Problem:
Solution for 8-Queens Problem:
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
Cryptarithmetic Puzzle:
Solutions:
9567 + 1085 = 10652 {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2}
2. Implement A* and memory bounded A* algorithms.
Program:
import heapq
visited = {initial_state: 0}
while open_list:
cost, current_state, path = heapq.heappop(open_list)
if current_state == goal_state:
return path
zero_pos = current_state.index(0)
x, y = divmod(zero_pos, 3)
g = len(path) + 1
h = manhattan_distance(new_state, goal_state)
new_cost = g + h
return None
if state == goal_state:
return f, path
min_bound = float('inf')
zero_pos = state.index(0)
x, y = divmod(zero_pos, 3)
new_g = g + 1
new_bound, new_path = ida_star_recursive(new_state, new_g, bound, goal_state, path +
[new_state])
while True:
bound, path = ida_star_recursive(initial_state, 0, bound, goal_state, [initial_state])
if path is not None:
return path
if bound == float('inf'):
return None
# Main Program
if __name__ == '__main__':
print("Select an algorithm to solve the 8-puzzle problem:")
print("1. A* Algorithm")
print("2. IDA* Algorithm")
initial_state = (3, 1, 2, 4, 7, 5, 6, 8, 0)
goal_state = (0, 1, 2, 3, 4, 5, 6, 7, 8)
if choice == 1:
print("Solving using A* Algorithm...")
path = a_star(initial_state, goal_state)
if path:
print("Solution found!")
for step in path:
print(step)
else:
print("No solution found.")
elif choice == 2:
print("Solving using IDA* Algorithm...")
path = ida_star(initial_state, goal_state)
if path:
print("Solution found!")
for step in path:
print(step)
else:
print("No solution found.")
else:
print("Invalid choice!")
OUTPUT:
A* Algorithm:
Select an algorithm to solve the 8-puzzle problem:
1. A* Algorithm
2. IDA* Algorithm
Enter your choice: 1
Solving using A* Algorithm...
Solution found!
(3, 1, 2, 4, 7, 5, 6, 8, 0)
(3, 1, 2, 4, 7, 5, 6, 0, 8)
(3, 1, 2, 4, 7, 5, 0, 6, 8)
(3, 1, 2, 4, 7, 0, 5, 6, 8)
(3, 1, 2, 4, 0, 7, 5, 6, 8)
(3, 1, 2, 0, 4, 7, 5, 6, 8)
(3, 1, 0, 2, 4, 7, 5, 6, 8)
(3, 0, 1, 2, 4, 7, 5, 6, 8)
(0, 3, 1, 2, 4, 7, 5, 6, 8)
(1, 3, 0, 2, 4, 7, 5, 6, 8)
(1, 3, 2, 0, 4, 7, 5, 6, 8)
(1, 3, 2, 4, 0, 7, 5, 6, 8)
(1, 3, 2, 4, 7, 0, 5, 6, 8)
(1, 3, 2, 4, 7, 5, 0, 6, 8)
(1, 3, 2, 4, 7, 5, 6, 0, 8)
(1, 3, 2, 4, 7, 5, 6, 8, 0)
IDA* Algorithm:
Select an algorithm to solve the 8-puzzle problem:
1. A* Algorithm
2. IDA* Algorithm
Enter your choice: 2
Solving using IDA* Algorithm...
Solution found!
(3, 1, 2, 4, 7, 5, 6, 8, 0)
(3, 1, 2, 4, 7, 5, 6, 0, 8)
(3, 1, 2, 4, 7, 5, 0, 6, 8)
(3, 1, 2, 4, 7, 0, 5, 6, 8)
(3, 1, 2, 4, 0, 7, 5, 6, 8)
(3, 1, 2, 0, 4, 7, 5, 6, 8)
(3, 1, 0, 2, 4, 7, 5, 6, 8)
(3, 0, 1, 2, 4, 7, 5, 6, 8)
(0, 3, 1, 2, 4, 7, 5, 6, 8)
(1, 3, 0, 2, 4, 7, 5, 6, 8)
(1, 3, 2, 0, 4, 7, 5, 6, 8)
(1, 3, 2, 4, 0, 7, 5, 6, 8)
(1, 3, 2, 4, 7, 0, 5, 6, 8)
(1, 3, 2, 4, 7, 5, 0, 6, 8)
(1, 3, 2, 4, 7, 5, 6, 0, 8)
(1, 3, 2, 4, 7, 5, 6, 8, 0)
if maximizingPlayer:
best = MIN
# Recur for left and right children
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i, False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)
# Alpha Beta Pruning
if beta <= alpha:
break
return best
else:
best = MAX
# Recur for left and right children
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i, True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)
# Alpha Beta Pruning
if beta <= alpha:
break
return best
# Driver Code
if __name__ == "__main__":
values = [3, 5, 6, 9, 1, 2, 0, -1]
print("The optimal value is:", minimax(0, 0, True, values, MIN, MAX))
OUTPUT:
The optimal value is : 5
4. Solve constraint satisfaction problems
Program:
def backtrack(assignment):
# Runs backtracking search to find an assignment
if len(assignment) == len(VARIABLES):
return assignment
var = select_unassigned_variable(assignment)
for value in DOMAIN:
if consistent(var, value, assignment):
assignment[var] = value
result = backtrack(assignment)
if result is not None:
return result
assignment.pop(var)
return None
def select_unassigned_variable(assignment):
# Chooses a variable not yet assigned, in order
for var in VARIABLES:
if var not in assignment.keys():
return var
solution = backtrack(dict())
print(solution)
OUTPUT:
{'csc': 'Monday', 'math': 'Tuesday', 'phy': 'Tuesday', 'che': 'Monday', 'tam': 'Monday', 'eng':
'Wednesday', 'bio': 'Tuesday'}
5. Implement propositional model checking algorithms
Program:
import re
class Literal:
def __init__(self, name, sign=True):
self.name = str(name)
self.sign = sign
def __neg__(self):
return Literal(self.name, False)
def __str__(self):
return str(self.name)
def __repr__(self):
if self.sign:
return '%r' % str(self.__str__())
else:
return '%r' % str("-" + self.__str__())
def CNFconvert(KB):
storage = []
for i in KB:
i = list(i)
for j in i:
j = str(j)
storage.append(i)
return storage
def VariableSet(KB):
KB = eval((CNFconvert(KB).__str__()))
storage = []
for obj in KB:
for item in obj:
if item[0] == '-' and item[1:] not in storage:
storage.append(str(item[1:]))
elif item not in storage and item[0] != '-':
storage.append(str(item))
return storage
def Negativeofx(x):
check = re.match("-", str(x))
if (check):
return str(x[1:])
else:
return "-"+str(x)
def unitResolution(clauses):
literalholder = {}
i=0
while i < len(clauses):
newClauses = []
clause = clauses[i]
if (len(clause) == 1):
literal = str(clause[0])
pattern = re.match("-", literal)
if (pattern):
nx = literal[1:]
literalholder[nx] = False
else:
nx = "-"+literal
literalholder[literal] = True
for item in clauses:
if item != clauses[i]:
if (nx in item):
item.remove(nx)
newClauses.append(item)
i=0
clauses = newClauses
else:
i += 1
return literalholder, clauses
def DPLL(KB):
KB = eval((CNFconvert(KB).__str__()))
varList = VariableSet(KB)
result = dpll(KB, varList)
if result == 'notsatisfiable':
return False
else:
for i in varList:
if i in result and result[i] == True:
result[i] = 'true'
elif i in result and result[i] == False:
result[i] = 'false'
else:
result[i] = 'free'
return [True, result]
# Example Usage
A = Literal('A')
B = Literal('B')
C = Literal('C')
D = Literal('D')
KB = [{A, B}, {A, -C}, {-A, B, D}]
print(DPLL(KB))
OUTPUT:
[True, {'B': 'true', 'A': 'true', 'C': 'free', 'D': 'free'}]
6. Implement forward chaining, backward chaining, and resolution strategies
Program:
while changes:
changes = False
for rule in rules:
if all(facts.get(cond, False) for cond in rule["if"]) and rule["then"] not in inferred:
inferred.add(rule["then"])
facts[rule["then"]] = True
changes = True
return inferred
# Backward chaining
is_goal_achievable = backward_chaining(goal, rules, facts)
print(f"Can we achieve goal '{goal}' (Backward Chaining)?", is_goal_achievable)
# Resolution Strategy
result = resolution_strategy(cnf_rules, goal)
print(f"Is the goal '{goal}' achievable using Resolution Strategy?", result)
OUTPUT:
Inferred facts (Forward Chaining): {'bird'}
Can we achieve goal 'cloudy' (Backward Chaining)? True
Is the goal 'cloudy' achievable using Resolution Strategy? True
7. Build naïve Bayes models
Program:
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
# The dataset
iris = datasets.load_iris()
X = iris.data
Y = iris.target
# Making predictions
model_predictions = model.predict(X_test)
Confusion Matrix:
[[16 0 0]
[ 0 17 0]
[ 0 0 17]]
import numpy as np
from sklearn import datasets
import torch
import torch.nn as nn
import torch.optim as optim
import torchbnn as bnn
import matplotlib.pyplot as plt
# the dataset
dataset = datasets.load_iris()
data = dataset.data
target = dataset.target
OUTPUT: