0% found this document useful (0 votes)
13 views15 pages

Test (Final)

Uploaded by

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

Test (Final)

Uploaded by

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

1.a Implement depth first search algorithm.

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)

___________________________________________________________________________________
_______________________________________________________

1.b Implement breadth first search algorithm.

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'])
}
#IMPLEMENT LOGIC OF BFS
def bfs(start) :
queue=[start]
levels={}
levels[start]=0
visited=set([start])
while queue:
node=queue.pop(0)
neighbours=graph[node]
for neighbour in neighbours:
if neighbour not in visited:
queue.append(neighbour)
visited.add(neighbour)
levels[neighbour]=levels[node]+1
print(levels)
return visited

print(str(bfs('A')))

def bfs_paths(graph,start,goal):
queue=[(start,[start])]
while queue:
(vertex,path)=queue.pop(0)
for next in graph[vertex]-set(path):
if next == goal:
yield path+[next]
else:
queue.append((next,path+[next]))
result=list(bfs_paths(graph,'A', 'F'))
print(result)
def shortest_path(graph,start,goal):
try:
return next(bfs_paths(graph,start,goal))
except StopIteration:
return None
result=shortest_path(graph,'A','F')
print(result)

___________________________________________________________________________________
_______________________________________________________

2.a Simulate 4-Queen / N-Queen problem.

class QueenChessBoard:
def __init__(self, size): # Corrected constructor name
self.size = size
self.columns = []

def place_in_next_row(self, column):


self.columns.append(column)

def remove_in_current_row(self):
return self.columns.pop()

def is_this_column_safe_in_next_row(self, column):


row = len(self.columns)

for queen_column in self.columns:


if column == queen_column:
return False

for queen_row, queen_column in enumerate(self.columns):


if queen_column - queen_row == column - row:
return False

for queen_row, queen_column in enumerate(self.columns):


if ((self.size - queen_column) - queen_row == (self.size - column) -
row):
return False
return True

def display(self):
for row in range(self.size):
for column in range(self.size):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()

def solve_queen(size):
"""Display a chessboard for each possible configuration of placing n queens
on an n x n chessboard and print the number of such configurations."""
board = QueenChessBoard(size)
number_of_solutions = 0

row = 0
column = 0

while True:
while column < size:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row += 1
column = 0
break
else:
column += 1

if (column == size or row == size):


if row == size:
board.display()
print()
number_of_solutions += 1

if row > 0:
board.remove_in_current_row()
row -= 1

try:
prev_column = board.remove_in_current_row()
except IndexError:
break

row -= 1
column = 1 + prev_column
else:
column = 0

print('Number of solutions:', number_of_solutions)

n = int(input('Enter n: '))
solve_queen(n)

___________________________________________________________________________________
_______________________________________________________

2.b Solve tower of Hanoi problem.

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

___________________________________________________________________________________
______________________________________________________

3.a Implement alpha beta search.

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
global root
global pruned
i = 0
for child in branch:
if isinstance(child, list):
(nalpha, nbeta) = children(child, depth + 1, alpha, beta)
if depth % 2 == 1:
beta = min(nalpha, beta)
else:
alpha = max(nbeta, alpha)
branch[i] = alpha if depth % 2 == 0 else beta
i += 1
else:
if depth % 2 == 0 and alpha < child:
alpha = child
if depth % 2 == 1 and beta > child:
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 tree
global pruned
global root
(alpha, beta) = children(tree, start, upper, lower)

if __name__ == "__main__":
print("(alpha, beta): ", alpha, beta)
print("Result: ", tree)
print("Times pruned: ", pruned)
return (alpha, beta, tree, pruned)

if __name__ == "__main__":
alphabeta(None)

___________________________________________________________________________________
_____________________________________________________

3.b Implement hill climbing problem

import math

increment = 0.1
startingPoint = [1, 1]
point1 = [1, 5]
point2 = [6, 4]
point3 = [5, 2]
point4 = [2, 1]

def distance(x1, y1, x2, y2):


# Return the actual distance instead of squared distance
dist = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))
return dist

def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
d1 = distance(x1, y1, px1, py1)
d2 = distance(x1, y1, px2, py2)
d3 = distance(x1, y1, px3, py3)
d4 = distance(x1, y1, px4, py4)
return d1 + d2 + d3 + d4

def newDistance(x1, y1, point1, point2, point3, point4):


d1 = [x1, y1]
d1temp = sumOfDistances(x1, y1, point1[0], point1[1], point2[0], point2[1],
point3[0], point3[1], point4[0], point4[1])
d1.append(d1temp)
return d1

minDistance = sumOfDistances(startingPoint[0], startingPoint[1], point1[0],


point1[1], point2[0], point2[1], point3[0], point3[1], point4[0], point4[1])
flag = True

def newPoints(minimum, d1, d2, d3, d4):


if d1[2] == minimum:
return [d1[0], d1[1]]
elif d2[2] == minimum:
return [d2[0], d2[1]]
elif d3[2] == minimum:
return [d3[0], d3[1]]
elif d4[2] == minimum:
return [d4[0], d4[1]]

i = 1
while flag:
d1 = newDistance(startingPoint[0] + increment, startingPoint[1], point1,
point2, point3, point4)
d2 = newDistance(startingPoint[0] - increment, startingPoint[1], point1,
point2, point3, point4)
d3 = newDistance(startingPoint[0], startingPoint[1] + increment, point1,
point2, point3, point4)
d4 = newDistance(startingPoint[0], startingPoint[1] - increment, point1,
point2, point3, point4)
print(i, ' ', round(startingPoint[0], 2), round(startingPoint[1], 2))
minimum = min(d1[2], d2[2], d3[2], d4[2])
if minimum < minDistance:
startingPoint = newPoints(minimum, d1, d2, d3, d4)
minDistance = minimum
else:
flag = False # Exit the loop if no minimum is found
i += 1

___________________________________________________________________________________
_____________________________________________________

4.a Implement A* algorithm.

from simpleai.search import SearchProblem, astar

GOAL = 'HELLO WORLD'

class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
else:
return []

def result(self, state, action):


return state + action

def is_goal(self, state):


return state == GOAL

def heuristic(self, state):


# how far are we from the goal?
wrong = sum([1 if state[i] != GOAL[i] else 0
for i in range(len(state))])
missing = len(GOAL) - len(state)
return wrong + missing

problem = HelloProblem(initial_state='')
result = astar(problem)

print(result.state)
print(result.path())

___________________________________________________________________________________
___________________________________________________

4.b Solve water jug problem.

# 3 water jugs capacity -> (x,y,z) where x>y>z


# initial state (12,0,0)
# final state (6,6,0)

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 = {}
# store solution path
ans = []

def get_all_states(state):
# Let the 3 jugs be called a, b, c
a = state[0]
b = state[1]
c = state[2]
if a == 6 and b == 6:
ans.append(state)
return True
# if current state is already visited earlier
if (a, b, c) in memory:
return False
memory[(a, b, c)] = 1
# 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)

___________________________________________________________________________________
_____________________________________________________

5.a Simulate tic – tac – toe game using min-max algorithm

import os
import time

board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'

# This Function Draws Game Board


def DrawBoard():
print(" %c | %c | %c " % (board[1], board[2], board[3]))
print("---|---|---")
print(" %c | %c | %c " % (board[4], board[5], board[6]))
print("---|---|---")
print(" %c | %c | %c " % (board[7], board[8], board[9]))
print(" | | ")
# This Function Checks position is empty or not
def CheckPosition(x):
return board[x] == ' '

# This Function Checks player has won or not


def CheckWin():
global Game
# Horizontal winning condition
if (board[1] == board[2] == board[3] != ' ' or
board[4] == board[5] == board[6] != ' ' or
board[7] == board[8] == board[9] != ' '):
Game = Win
# Vertical Winning Condition
elif (board[1] == board[4] == board[7] != ' ' or
board[2] == board[5] == board[8] != ' ' or
board[3] == board[6] == board[9] != ' '):
Game = Win
# Diagonal Winning Condition
elif (board[1] == board[5] == board[9] != ' ' or
board[3] == board[5] == board[7] != ' '):
Game = Win
# Match Tie or Draw Condition
elif all(pos != ' ' for pos in board[1:]):
Game = Draw
else:
Game = Running

print("Tic-Tac-Toe Game")
print("Player 1 [X] --- Player 2 [O]\n")
print("Please Wait...")
time.sleep(1)

while Game == Running:


os.system('cls' if os.name == 'nt' else 'clear')
DrawBoard()
Mark = 'X' if player % 2 != 0 else 'O'
print(f"Player {1 if player % 2 != 0 else 2}'s chance")

try:
choice = int(input("Enter the position between [1-9] where you want to
mark: "))
if choice < 1 or choice > 9:
print("Invalid position! Please choose a number between 1 and 9.")
continue
except ValueError:
print("Invalid input! Please enter a number.")
continue

if CheckPosition(choice):
board[choice] = Mark
player += 1
CheckWin()
else:
print("Position already taken! Please choose another.")

os.system('cls' if os.name == 'nt' else 'clear')


DrawBoard()
if Game == Draw:
print("Game Draw")
elif Game == Win:
player -= 1
print(f"Player {1 if player % 2 != 0 else 2} Won")

___________________________________________________________________________________
_____________________________________________________

5.b Shuffle deck of cards.

import itertools
import random

# Create a deck of cards


deck = list(itertools.product(range(1, 14), ['Spades', 'Hearts', 'Diamonds',
'Clubs']))

# Shuffle the deck


random.shuffle(deck)

# Draw five cards


print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])

___________________________________________________________________________________
______________________________________________________

5.b Shuffle deck of cards.(2nd)

import random

# List holders for card faces and suits


cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

# Add numbers 2-10 to cardfaces as strings


for i in range(2, 11):
cardfaces.append(str(i))

# Add royal faces (J, Q, K, A) to cardfaces


for j in range(4):
cardfaces.append(royals[j])

# Create the deck of cards by combining faces and suits


for k in range(4):
for l in range(13):
card = (cardfaces[l] + " of " + suits[k])
deck.append(card)
# Shuffle the deck
random.shuffle(deck)

# Display the shuffled deck


for m in range(52):
print(deck[m])

___________________________________________________________________________________
___________________________________________________

6a. Design an application to simulate number puzzle problem

from simpleai.search import SearchProblem, astar

GOAL = '''1-2-3
4-5-6
7-8-e'''

INITIAL = '''4-1-2
7-e-3
8-5-6'''

def list_to_string(list_):
return '\n'.join(['-'.join(row) for row in list_])

def string_to_list(string_):
return [row.split('-') for row in string_.split('\n')]

def find_location(rows, element_to_find):


'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic

# we create a cache for the goal position of each piece, so we don't have to
# recalculate them every time
goal_positions = {}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
goal_positions[number] = find_location(rows_goal, number)

class EigthPuzzleProblem(SearchProblem):
def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions

def result(self, state, action):


'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, action)
rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[row_e]
[col_e]
return list_to_string(rows)

def is_goal(self, state):


'''Returns true if a state is the goal state.'''
return state == GOAL

def cost(self, state1, action, state2):


'''Returns the cost of performing an action. No useful on this problem, but
needed.'''
return 1

def heuristic(self, state):


'''Returns an estimation of the distance from a state to the goal.
We are using the manhattan distance.'''
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
row_n_goal, col_n_goal = goal_positions[number]
distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)
return distance

result = astar(EigthPuzzleProblem(INITIAL))
for action, state in result.path():
print('Move number', action)
print(state)

___________________________________________________________________________________
___________________________________________________

6b. Write a program to solve Missionaries and Cannibals problem.

___________________________________________________________________________________
___________________________________________________

7.a Solve constraint satisfaction problem.

% Define the subjects


subject(math).
subject(physics).
subject(chemistry).

% Define the constraints


% Alice does not like Math
constraint(alice, Subject) :- Subject \= math.

% Bob prefers Physics


constraint(bob, physics).

% Charlie does not like Chemistry


constraint(charlie, Subject) :- Subject \= chemistry.

% The main predicate to solve the problem


assign_subjects(Assignments) :-
% List of students
Students = [alice, bob, charlie],

% List of subjects
Subjects = [math, physics, chemistry],

% Create an empty list to hold the assignments


Assignments = [(alice, _), (bob, _), (charlie, _)],

% Assign subjects to students


assign(Students, Subjects, Assignments).

% Helper predicate to assign subjects to students


assign([], [], []).

assign([Student | RemainingStudents], Subjects, [(Student, Subject) |


RemainingAssignments]) :-
% Choose a subject
select(Subject, Subjects, RemainingSubjects),

% Check the constraint for the current student


constraint(Student, Subject),

% Recursively assign the remaining students


assign(RemainingStudents, RemainingSubjects, RemainingAssignments).

___________________________________________________________________________________
_________________________________________________

8.a Derive the expressions based on Associative Law.

associative_law(A,B,C,Result):-
Result is A+(B+C).

expression1(12,13,14).
expression2(5,6,7).

derive_results :-
expression1(A,B,C),
associative_law(A,B,C,Result1),
expression2(X,Y,Z),
associative_law(X,Y,Z,Result2),
write("Result1 : "),write(Result1),nl,
write("Result2 : "),write(Result2),nl.
__________________________________________________________________

8.b Derive the expressions based on Distributive Law

associative_law(A,B,C,Result):-
Result is A*(B+C).

expression1(12,13,14).
expression2(5,6,7).

derive_results :-
expression1(A,B,C),
associative_law(A,B,C,Result1),
expression2(X,Y,Z),
associative_law(X,Y,Z,Result2),
write("Result1 : "),write(Result1),nl,
write("Result2 : "),write(Result2),nl.

___________________________________________________________________________________
_________________________________________________

9.a Derive the predicate. (for e.g.: Sachin is batsman, batsman is cricketer)
- > Sachin is Cricketer

batsman(sachin).
cricketer(X):-batsman(X).

___________________________________________________________________________________
_________________________________________________

10.a Write a program which contains three predicates: male, female, parent. Make
rules for
following family relations: father, mother, grandfather, grandmother, brother,
sister, uncle,
aunt, nephew and niece, cousin. Question: i. Draw Family Tree. ii. Define: Clauses,
Facts,
Predicates and Rules with conjunction and disjunction

female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
haschild(X):- parent(X,_).
sister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.

You might also like