Professional Documents
Culture Documents
In [1]:
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
visited.append(node)
queue.append(node)
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
5 3 7 2 4 8
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
print (node)
visited.add(node)
# Driver Code
N Queen Problem
In [3]:
# Python program to solve N Queen
global N
N = 4
def printSolution(board):
for i in range(N):
for j in range(N):
print()
# attacking queens
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
return True
board[i][col] = 0
return False
# feasible solutions.
def solveNQ():
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
if solveNQUtil(board, 0) == False:
return False
printSolution(board)
return True
solveNQ()
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
True
Out[3]:
y = 3
z = 2
if(b == 0):
return a
return gcd(b, a % b)
return False
if(z == 0):
return True
else:
return False
return True
else:
return False
In [4]:
from collections import deque
m = {}
isSolvable = False
path = []
q = deque()
q.append((0, 0))
# Current state
u = q.popleft()
continue
continue
path.append([u[0], u[1]])
m[(u[0], u[1])] = 1
isSolvable = True
if (u[0] == target):
if (u[1] != 0):
path.append([u[0], 0])
else:
if (u[0] != 0):
path.append([0, u[1]])
sz = len(path)
for i in range(sz):
path[i][1], ")")
break
c = u[0] + ap
d = u[1] - ap
q.append([c, d])
c = u[0] - ap
d = u[1] + ap
q.append([c, d])
# Empty Jug2
q.append([a, 0])
# Empty Jug1
q.append([0, b])
if (not isSolvable):
# Driver code
if __name__ == '__main__':
( 0 , 0 )
( 0 , 3 )
( 4 , 0 )
( 4 , 3 )
( 3 , 0 )
( 1 , 3 )
( 3 , 3 )
( 4 , 2 )
( 0 , 2 )
8 Puzzle Problem
In [4]:
# Python3 program to print the path from root
# puzzle is solvable
import copy
# puzzle(n=4) to 24 puzzle(n=5)...
n = 3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:
return False
# Node structure
class node:
cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.level = level
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
return count
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
cost, level)
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print()
# matrix coordinate
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
pq = priorityQueue()
empty_tile_pos, cost, 0)
pq.push(root)
# the list.
minimum = pq.pop()
if minimum.cost == 0:
# destination;
printPath(minimum)
return
for i in range(n):
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]):
minimum.empty_tile_p
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
# Driver Code
# Initial configuration
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
# initial configuration
empty_tile_pos = [ 1, 2 ]
1 2 3
5 6 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
print('-+-+-')
print('-+-+-')
print("\n")
def spaceIsFree(position):
return True
else:
return False
if spaceIsFree(position):
board[position] = letter
printBoard(board)
if (checkDraw()):
print("Draw!")
print("No. of moves ",n )
exit()
if checkForWin():
if letter == 'X':
print("You win!")
exit()
else:
print("Bot wins!")
exit()
return
else:
insertLetter(letter, position)
return
def checkForWin():
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] != ' '):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] != ' '):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] != ' '):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] != ' '):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] != ' '):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] != ' '):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] != ' '):
return True
else:
return False
def checkWhichMarkWon(mark):
return True
return True
return True
return True
return True
return True
return True
return True
else:
return False
def checkDraw():
return False
return True
def playerMove():
insertLetter(player, position)
return
def compMove():
bestScore = -800
bestMove = 0
board[key] = bot
bestScore = score
bestMove = key
insertLetter(bot, bestMove)
return
if (checkWhichMarkWon(bot)):
return 1
elif (checkWhichMarkWon(player)):
return -1
elif (checkDraw()):
return 0
if (isMaximizing):
bestScore = -800
board[key] = bot
bestScore = score
return bestScore
else:
bestScore = 800
board[key] = player
bestScore = score
return bestScore
printBoard(board)
print("You go first! Don't worry you will not lose provided you use your brain ")
print("1, 2, 3 ")
print("4, 5, 6 ")
print("7, 8, 9 ")
print("\n")
player = 'X'
bot = 'O'
n=0
n=n+1
playerMove()
n=n+1
compMove()
| |
-+-+-
| |
-+-+-
| |
You go first! Don't worry you will not lose provided you use your brain
1, 2, 3
4, 5, 6
7, 8, 9
X| |
-+-+-
| |
-+-+-
| |
X| |
-+-+-
|O|
-+-+-
| |
X| |
-+-+-
X|O|
-+-+-
| |
X| |
-+-+-
X|O|
-+-+-
O| |
X| |X
-+-+-
X|O|
-+-+-
O| |
X|O|X
-+-+-
X|O|
-+-+-
O| |
X|O|X
-+-+-
X|O|
-+-+-
O| |X
X|O|X
-+-+-
X|O|
-+-+-
O|O|X
Bot wins!
No. of moves 8
# Start by doing DFS with a depth of 1, keep doubling depth until we reach the "
depth = 1
# One of the "end nodes" of the search with this depth has to still have chi
result, bottom_reached = iterative_deepening_dfs_rec(start, target, 0, depth
if result is not None:
# We've found the goal node while doing DFS with this max depth
return result
# We haven't found the goal node, but there are still deeper nodes to search
depth *= 2
# We haven't found the node and there were no more nodes that still have childre
return None
if node["value"] == target:
if current_depth == max_depth:
if len(node["children"]) > 0:
else:
bottom_reached = True
for i in range(len(node["children"])):
# We've found the goal node while going down that child
# We've gone through all children and not found the goal node
In [ ]:
def __init__(self,data,level,fval):
""" Initialize the node with the data, level of the node and the calculated
self.data = data
self.level = level
self.fval = fval
def generate_child(self):
""" Generate child nodes from the given node by moving the blank space
x,y = self.find(self.data,'_')
""" val_list contains position values for moving the blank space in either o
the 4 directions [up,down,left,right] respectively. """
val_list = [[x,y-1],[x,y+1],[x-1,y],[x+1,y]]
children = []
for i in val_list:
child = self.shuffle(self.data,x,y,i[0],i[1])
child_node = Node(child,self.level+1,0)
children.append(child_node)
return children
def shuffle(self,puz,x1,y1,x2,y2):
""" Move the blank space in the given direction and if the position value ar
of limits the return None """
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None
def copy(self,root):
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp
def find(self,puz,x):
""" Specifically used to find the position of the blank space """
for i in range(0,len(self.data)):
for j in range(0,len(self.data)):
if puz[i][j] == x:
return i,j
class Puzzle:
def __init__(self,size):
""" Initialize the puzzle size by the specified size,open and closed lists t
self.n = size
self.open = []
self.closed = []
def accept(self):
puz = []
for i in range(0,self.n):
puz.append(temp)
return puz
def f(self,start,goal):
""" Heuristic Function to calculate hueristic value f(x) = h(x) + g(x) """
return self.h(start.data,goal)+start.level
def h(self,start,goal):
temp = 0
for i in range(0,self.n):
for j in range(0,self.n):
temp += 1
return temp
def process(self):
count = 0
start = self.accept()
goal = self.accept()
start = Node(start,0,0)
start.fval = self.f(start,goal)
self.open.append(start)
print("\n\n")
while True:
if count>20:
break
cur = self.open[0]
print("")
print(" | ")
print(" | ")
for i in cur.data:
for j in i:
print(j,end=" ")
print("")
count+=1
""" If the difference between current and goal node is 0 we have reached
if(self.h(cur.data,goal) == 0):
break
for i in cur.generate_child():
i.fval = self.f(i,goal)
self.open.append(i)
self.closed.append(cur)
del self.open[0]
puz = Puzzle(3)
puz.process()
b c a a
a b c c
b c c b
import sys
import time
class Direction:
OLD_TO_NEW = 1
NEW_TO_OLD = 0
class CONST:
self.MAX_M = MAX_M
self.MAX_C = MAX_C
self.CAP_BOAT = CAP_BOAT
self.MAX_TIME = MAX_TIME_S
self.MAX_NODES = MAX_NODES
# INITIAL_STATE = None
MAX_M = 30
MAX_C = 30
CAP_BOAT = 20
CNST = None
class State(object):
self.cannibals = cannibals
self.dir = dir
self.action = ""
self.level = level
self.missionariesPassed = missionariesPassed
self.cannibalsPassed = cannibalsPassed
self.CONSTANTS = CONSTS
self.moves = moves
global MAX_M
global MAX_C
global CAP_BOAT
global CNST
CNST = CONSTS
MAX_M = CONSTS.MAX_M
MAX_C = CONSTS.MAX_C
CAP_BOAT = CONSTS.CAP_BOAT
def successors(self):
listChild = []
return listChild
if self.dir == Direction.OLD_TO_NEW:
sgn = -1
else:
sgn = 1
for i in self.moves:
(m, c) = i
return listChild
if newState.isValid():
def isValid(self):
# obvious
return False
return True
def isGoalState(self):
def __repr__(self):
return "\n%s\n\n< @Depth:%d State (%d, %d, %d, %d, %d) >" % (
def __hash__(self):
import time
class Graph:
def __init__(self):
self.bfs_parent = {}
self.dfs_parent = {}
self.expandedBFS = 0
self.expandedDFS = 0
self.expandedBFS = 0
self.bfs_parent[s] = None
s.level = 0
start_time = time.time()
queue = [s]
while queue:
self.expandedBFS += 1
u = queue.pop(0)
if u.isGoalState():
self.bfs_parent[TERMINAL_STATE] = u
return self.bfs_parent
t = time.time() - start_time
return {}
for v in reversed(u.successors()):
v.level = u.level + 1
queue.append(v)
return {}
self.expandedDFS = 0
self.dfs_parent[s] = None
start_time = time.time()
stack = [s]
while stack:
u = stack.pop()
self.expandedDFS += 1
if u.isGoalState():
return self.dfs_parent
t = time.time() - start_time
return {}
for v in u.successors():
stack.append(v)
return {}
if tail is None:
return
stack = []
stack.append(tail)
tail = parentList[tail]
while stack:
print(stack.pop())
CON_IN = sys.stdin
CON_OUT = sys.stdout
# Generate All possible next moves for each state to reduce number of iterations on
def genPossibleMoves(CAP_BOAT):
moves = []
if 0 < m < c:
continue
moves.append((m, c))
return moves
print("\n\nBFS :: \n")
start_time = time.time()
p = g.BFS(INITIAL_STATE)
end_time = time.time()
# print("Printing Solution...")
if len(p):
g.printPath(p, TERMINAL_STATE)
else:
print("No Solution")
print("\n\nDFS :: \n")
start_time = time.time()
p = g.DFS(INITIAL_STATE)
end_time = time.time()
if len(p):
g.printPath(p, TERMINAL_STATE)
else:
print("No Solution")
def main():
m = int(input("m="))
print(m, end="\n")
c = int(input("c="))
print(c, end="\n")
k = int(input("k="))
print(k, end="\n")
# t=10
t = int(10)
#print(t, end="\n")
n = int(100000)
#print(n, end="\n")
# t=10
# n=100000
CNST = CONST(m, c, k, t, n)
moves = genPossibleMoves(CNST.CAP_BOAT)
g = Graph()
sys.stdout = CON_OUT
print("\nRunning BFS>")
runBFS(g, INITIAL_STATE)
sys.stdout = CON_OUT
print("Executed BFS>")
print("\nRunning DFS>")
runDFS(g, INITIAL_STATE)
sys.stdout = CON_OUT
print("Executed DFS>")
if __name__ == '__main__':
main()
Burglary Alarm
In [3]:
# Import libraries
import pgmpy.models
import pgmpy.inference
import networkx as nx
('Earthquake', 'Alarm'),
('Alarm', 'JohnCalls'),
('Alarm', 'MaryCalls')])
evidence_card=[2, 2])
# Probability that John calls (True, False) given that the alarm has sounded
[0.10, 0.95]],
evidence=['Alarm'],
evidence_card=[2])
# Probability that Mary calls (True, False) given that the alarm has sounded
[0.30, 0.99]],
evidence=['Alarm'],
evidence_card=[2])
model.check_model()
print(cpd_burglary)
print()
print(cpd_earthquake)
print()
print(cpd_alarm)
print()
print(cpd_john)
print()
print(cpd_mary)
print()
nx.draw(model, with_labels=True)
infer = pgmpy.inference.VariableElimination(model)
# Calculate the probability of a burglary if John and Mary calls (0: True, 1: False)
posterior_probability = infer.query(['Burglary'], evidence={'JohnCalls': 0, 'MaryCal
# Print posterior probability
print(posterior_probability)
print()
print()
+-------------+-------+
| Burglary(0) | 0.001 |
+-------------+-------+
| Burglary(1) | 0.999 |
+-------------+-------+
+---------------+-------+
| Earthquake(0) | 0.002 |
+---------------+-------+
| Earthquake(1) | 0.998 |
+---------------+-------+
+------------+---------------+---------------+---------------+---------------+
+------------+---------------+---------------+---------------+---------------+
+------------+---------------+---------------+---------------+---------------+
+------------+---------------+---------------+---------------+---------------+
+------------+---------------+---------------+---------------+---------------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
+--------------+----------+----------+
---------------------------------------------------------------------------
C:\ProgramData\Anaconda3\lib\site-packages\networkx\utils\decorators.py in _random_s
tate(func, *args, **kwargs)
395 try:
The above exception was the direct cause of the following exception:
<ipython-input-3-c7e2eb4ab24f> in <module>
50 print()
C:\ProgramData\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw(G, p
os, ax, **kwds)
122
124 ax.set_axis_off()
125 plt.draw_if_interactive()
C:\ProgramData\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_netw
orkx(G, pos, arrows, with_labels, **kwds)
331
334
C:\ProgramData\Anaconda3\lib\site-packages\networkx\utils\decorators.py in _random_s
tate(func, *args, **kwargs)
401
8 puzzle using a*
In [1]:
class Node:
def __init__(self,data,level,fval):
self.data = data
self.level = level
self.fval = fval
def generate_child(self):
x,y = self.find(self.data,'_')
val_list = [[x,y-1],[x,y+1],[x-1,y],[x+1,y]]
children = []
for i in val_list:
child = self.shuffle(self.data,x,y,i[0],i[1])
child_node = Node(child,self.level+1,0)
children.append(child_node)
return children
def shuffle(self,puz,x1,y1,x2,y2):
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None
def copy(self,root):
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp
def find(self,puz,x):
for i in range(0,len(self.data)):
for j in range(0,len(self.data)):
if puz[i][j] == x:
return i,j
class Puzzle:
def __init__(self,size):
self.n = size
self.open = []
self.closed = []
def accept(self):
puz = []
for i in range(0,self.n):
puz.append(temp)
return puz
def f(self,start,goal):
return self.h(start.data,goal)+start.level
def h(self,start,goal):
temp = 0
for i in range(0,self.n):
for j in range(0,self.n):
temp += 1
return temp
def process(self):
start = self.accept()
goal = self.accept()
start = Node(start,0,0)
start.fval = self.f(start,goal)
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
for i in cur.data:
for j in i:
print(j,end=" ")
print("")
if(self.h(cur.data,goal) == 0):
break
for i in cur.generate_child():
i.fval = self.f(i,goal)
self.open.append(i)
self.closed.append(cur)
del self.open[0]
puz = Puzzle(3)
puz.process()
1 2 3
_ 4 6
7 5 8
1 2 3
4 5 6
7 8 _
1 2 3
_ 4 6
7 5 8
1 2 3
4 _ 6
7 5 8
1 2 3
4 5 6
7 _ 8
1 2 3
4 5 6
7 8 _
visited_states = []
goal_=goal_state[3]
val=0
for i in range(len(curr_state)):
check_val=curr_state[i]
if len(check_val)>0:
for j in range(len(check_val)):
if check_val[j]!=goal_[j]:
# val-=1
val-=j
else:
# val+=1
val+=j
return val
def generate_next(curr_state,prev_heu,goal_state):
global visited_states
state = copy.deepcopy(curr_state)
for i in range(len(state)):
temp = copy.deepcopy(state)
if len(temp[i]) > 0:
elem = temp[i].pop()
for j in range(len(temp)):
temp1 = copy.deepcopy(temp)
if j != i:
curr_heu=heuristic(temp1,goal_state)
if curr_heu>prev_heu:
child = copy.deepcopy(temp1)
return child
return 0
def solution_(init_state,goal_state):
global visited_states
if (init_state == goal_state):
print (goal_state)
print("solution found!")
return
current_state = copy.deepcopy(init_state)
while(True):
visited_states.append(copy.deepcopy(current_state))
print(current_state)
prev_heu=heuristic(current_state,goal_state)
child = generate_next(current_state,prev_heu,goal_state)
if child==0:
return
current_state = copy.deepcopy(child)
def solver():
# maintaining a global visited to save all visited and avoid repetition & infini
global visited_states
# inputs
init_state = [[],[],[],['B','C','A','A']]
goal_state = [[],[],[],['A','B','C','D']]
# goal_state = [[],[],[],['A','D','C','B']]
solution_(init_state,goal_state)
solver()
In [ ]: