AI Practicals BSC It
AI Practicals BSC It
Code:
graph1 = {
'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E']) }
def dfs(graph, node, visited):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph,n, visited)
return visited
visited = dfs(graph1,'A', [])
print(visited)
Output:
(1.b) Implement breadth first search algorithm.
Code:
#sample graph implemented as a dictionary
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])
}
Output:
(2.a) Simulate 4-Queen/N-Queen problem.
Code:
def print_solutions(solutions):
"""Print all solutions in a human-readable format."""
i=0
if not solutions:
print("No solutions exist")
return
for solution in solutions:
for row in solution:
print(row)
print() # Newline for separating solutions
i=i+1
print("Number of Solutions: ",i)
def solve_n_queens(n):
"""Find all solutions to the N-Queens problem."""
def is_safe(board, row, col):
"""Check if placing a queen at (row, col) is safe."""
# Check the current row and column
for i in range(col):
if board[row][i] == 'Q':
return False
# Example usage:
n = int(input("Enter the size of the chessboard: ")) # Size of the chessboard
solutions = solve_n_queens(n)
print_solutions(solutions)
Output:
(2.b) Solve tower of Hanoi problem.
Code:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")
Output:
(3.a) Implement alpha beta search.
Code:
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
def children(branch, depth, alpha, beta):
global tree, pruned
for i, child in enumerate(branch):
if isinstance(child, list):
nalpha, nbeta = children(child, depth + 1, alpha, beta)
if depth % 2 == 0:
alpha = max(alpha, nbeta)
branch[i] = alpha
else:
beta = min(beta, nalpha)
else:
if depth % 2 == 0:
alpha = max(alpha, child)
else:
beta = min(beta, child)
if alpha >= beta:
pruned += 1
break
if depth == root:
tree = alpha if root == 0 else beta
return alpha, beta
def alphabeta(in_tree=tree, start=root, upper=-15, lower=15):
global pruned
alpha, beta = children(in_tree, start, upper, lower)
print(f"(alpha, beta): {alpha, beta}")
print(f"Result: {tree}")
print(f"Times pruned: {pruned}")
return alpha, beta, tree, pruned
if __name__ == "__main__":
alphabeta()
Output:
(3.b) Implement hill climbing problem.
Code:
import math
increment = 0.1
starting_point = [1, 1]
points = [[1, 5], [6, 4], [5, 2], [2, 1]]
while flag:
d1 = new_distance(starting_point[0] + increment, starting_point[1], points)
d2 = new_distance(starting_point[0] - increment, starting_point[1], points)
d3 = new_distance(starting_point[0], starting_point[1] + increment, points)
d4 = new_distance(starting_point[0], starting_point[1] - increment, points)
Code:
Output:
(4.b) Solve water jug problem.
Code:
capacity = (12,8,5)
# Maximum capacities of 3 jugs -> x,y,z
x = capacity[0]
y = capacity[1]
z = capacity[2]
# to mark visited states
memory = {}
def get_all_states(state):
# Let the 3 jugs be called a,b,c
a = state[0]
b = state[1]
c = state[2]
#empty jug a
if(a>0):
#empty a into b
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
ans.append(state)
return True
#empty a into c
if(a+c<=z):
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(z-c), b, z)) ):
ans.append(state)
return True
#empty jug b
if(b>0):
#empty b into a
if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):
ans.append(state)
return True
#empty b into c
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)
return True
#empty jug c
if(c>0):
#empty c into a
if(a+c<=x):
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
#empty c into b
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
return True
return False
initial_state = (12,0,0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
Output:
(5.a) Simulate tic-tac-toe game using min-max algorithm.
Code:
Import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'
print("Tic-Tac-Toe Game")
print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
time.sleep(1)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
print("Player 1's chance")
Mark = 'X'
else:
print("Player 2's chance")
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark : "))
if(CheckPosition(choice)):
board[choice] = Mark
player+=1
CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
Output:
(5.b) Shuffle deck of cards.
Code:
(# Python program to shuffle a deck of card using the module random anddraw 5 cards
# import modules
import itertools, random
Output:
(6.a) Design an application to simulate number puzzle problem.
Code:
class Puzzle:
def __init__(self, initial_state):
self.grid = [list(row) for row in initial_state]
self.empty_pos = self.find_empty_pos()
def find_empty_pos(self):
for r in range(3):
for c in range(3):
if self.grid[r][c] == 'e':
return (r, c)
return None
def is_solved(self):
goal = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', 'e']]
return self.grid == goal
def print_grid(self):
for row in self.grid:
print(" ".join(row))
print()
def main():
initial_state = [['4', '1', '2'], ['7', 'e', '3'], ['8', '5', '6']]
puzzle = Puzzle(initial_state)
if __name__ == "__main__":
main()
Output:
(7.a) Solve constraint satisfaction problem.
Code:
from __future__ import print_function
from simpleai.search import CspProblem, backtrack, min_conflicts,
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE,
LEAST_CONSTRAINING_VALUE
variables = ('WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T')
domains = dict((v, ['red', 'green', 'blue']) for v in variables)
def const_different(variables, values):
return values[0] != values[1] # expect the value of the neighbors to be different
constraints = [
(('WA', 'NT'), const_different),
(('WA', 'SA'), const_different),
(('SA', 'NT'), const_different),
(('SA', 'Q'), const_different),
(('NT', 'Q'), const_different),
(('SA', 'NSW'), const_different),
(('Q', 'NSW'), const_different),
(('SA', 'V'), const_different),
(('NSW', 'V'), const_different),
]
my_problem = CspProblem(variables, domains, constraints)
print(backtrack(my_problem))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE))
print(backtrack(my_problem,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(min_conflicts(my_problem))
Output:
(8.a) Derive the expression based on Associatiive Law.
Code:
#Practical 8a
def associative_law_addition(a, b, c):
# (a + b) + c == a + (b + c)
left_side = (a + b) + c
right_side = a + (b + c)
return left_side, right_side
# Test values
a=2
b=3
c=4
Output:
(8.b) Derive the expression based on Distributive Law.
Code:
#Practical 8b
def distributive_law(a, b, c):
# Calculate both sides of the distributive law
left_side = a * (b + c) # Left side: a * (b + c)
right_side = (a * b) + (a * c) # Right side: (a * b) + (a * c)
return left_side, right_side
# Test values
a=3
b=4
c=5
Output:
(9.a) Derive the predicate.
Code:
# Define facts as a dictionary where key is the subject and value is the predicate
facts = {
'Sachin': 'batsman',
'batsman': 'cricketer'
}
Output:
(10.a) Write a program which contains three predicates.
Code:
# Facts about individuals
male = {'John', 'Robert', 'Michael', 'Kevin'}
female = {'Mary', 'Patricia', 'Jennifer', 'Linda'}
parents = {
'John': ['Michael', 'Sarah'], # John is the father of Michael and Sarah
'Mary': ['Michael', 'Sarah'], # Mary is the mother of Michael and Sarah
'Robert': ['Kevin'], # Robert is the father of Kevin
'Patricia': ['Kevin'] # Patricia is the mother of Kevin
}
def is_father(father, child):
return father in male and child in parents.get(father, [])
Output: