Test (Final)
Test (Final)
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)
___________________________________________________________________________________
_______________________________________________________
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)
___________________________________________________________________________________
_______________________________________________________
class QueenChessBoard:
def __init__(self, size): # Corrected constructor name
self.size = size
self.columns = []
def remove_in_current_row(self):
return self.columns.pop()
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 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
n = int(input('Enter n: '))
solve_queen(n)
___________________________________________________________________________________
_______________________________________________________
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")
___________________________________________________________________________________
______________________________________________________
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
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)
___________________________________________________________________________________
_____________________________________________________
import math
increment = 0.1
startingPoint = [1, 1]
point1 = [1, 5]
point2 = [6, 4]
point3 = [5, 2]
point4 = [2, 1]
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
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
___________________________________________________________________________________
_____________________________________________________
class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
else:
return []
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
___________________________________________________________________________________
___________________________________________________
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)
___________________________________________________________________________________
_____________________________________________________
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("Please Wait...")
time.sleep(1)
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.")
___________________________________________________________________________________
_____________________________________________________
import itertools
import random
___________________________________________________________________________________
______________________________________________________
import random
___________________________________________________________________________________
___________________________________________________
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')]
# 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
result = astar(EigthPuzzleProblem(INITIAL))
for action, state in result.path():
print('Move number', action)
print(state)
___________________________________________________________________________________
___________________________________________________
___________________________________________________________________________________
___________________________________________________
% List of subjects
Subjects = [math, physics, chemistry],
___________________________________________________________________________________
_________________________________________________
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.
__________________________________________________________________
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.