SlideShare a Scribd company logo
1 of 7
Download to read offline
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, 8, 6, 3, 4, 5] import sys global
count def display_board( state ): #print "-------------" print " %i %i %i " %
(state[0], state[3], state[6]) #print "-------------" print " %i %i %i " % (state[1],
state[4], state[7]) #print "-------------" print " %i %i %i " % (state[2], state[5],
state[8]) #print "-------------" def move_up( state ): new_state = state[:] index =
new_state.index( 0 ) if index not in [0, 3, 6]: temp = new_state[index - 1]
new_state[index - 1] = new_state[index] new_state[index] = temp return
new_state else: return None def move_down( state ): new_state = state[:]
index = new_state.index( 0 ) if index not in [2, 5, 8]: temp = new_state[index + 1]
new_state[index + 1] = new_state[index] new_state[index] = temp
return new_state else: return None def move_left( state ): new_state = state[:]
index = new_state.index( 0 ) if index not in [0, 1, 2]: temp = new_state[index
- 3] new_state[index - 3] = new_state[index] new_state[index] = temp
return new_state else: return None def move_right( state ): new_state =
state[:] index = new_state.index( 0 ) if index not in [6, 7, 8]: temp =
new_state[index + 3] new_state[index + 3] = new_state[index]
new_state[index] = temp return new_state else: return None def
create_node( state, parent, operator, depth, cost ): return Node( state, parent, operator,
depth, cost ) def expand_node( node, nodes ): expanded_nodes = []
expanded_nodes.append( create_node( move_up( node.state ), node, "u", node.depth + 1, 0 ) )
expanded_nodes.append( create_node( move_down( node.state ), node, "d", node.depth + 1,
0 ) ) expanded_nodes.append( create_node( move_left( node.state ), node, "l", node.depth
+ 1, 0 ) ) expanded_nodes.append( create_node( move_right( node.state), node, "r",
node.depth + 1, 0 ) ) # Filter the list and remove the nodes that are impossible (move
function returned None) expanded_nodes = [node for node in expanded_nodes if node.state
!= None] #list comprehension! expanded_nodes = [node for node in expanded_nodes if
node not in nodes] #list comprehension! #expanded_nodes = [node for node in
expanded_nodes if node.state!= ((node.parent).parent).state] #list comprehension!
expanded_nodes1 = [] for node in expanded_nodes: temp=node
temp=temp.parent temp=temp.parent if temp==None:
expanded_nodes1.extend(expanded_nodes) break if node.state
!=temp.state: expanded_nodes1.append(node) return
expanded_nodes1 def bfs( start, goal ): nodes = [] count=0 # Create the queue
with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while
True: # We've run out of states, no solution. if len( nodes ) == 0:
return None # take the node from the front of the queue node = nodes.pop(0)
count=count+1 #display_board(node.state) # Append the move we made to
moves # if this node is the goal, return the moves it took to get here. if node.state
== goal: #display_board(node.state) moves = []
temp = node print count, " nodes " while True:
moves.insert(0, temp.operator) if temp.depth == 1:
break temp = temp.parent return moves
# Expand the node and add all the expansions to the front of the stack
#count=count+len(expand_node( node, nodes )) nodes.extend( expand_node( node,
nodes ) ) def dfs( start, goal, depth=12 ): depth_limit = depth # A list (can act as a
stack too) for the nodes. nodes = [] count=0 # Create the queue with the root node
in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've
run out of states, no solution. if len( nodes ) == 0: return None #
take the node from the front of the queue node = nodes.pop(0)
count=count+1; #if this node is the goal, return the moves it took to get here. if
node.state == goal: moves = [] temp = node print
count, " nodes " while True: moves.insert(0, temp.operator)
if temp.depth <= 1: break temp =
temp.parent return moves #,count # Add all the expansions to the beginning
of the stack if we are under the depth limit if node.depth < depth_limit:
expanded_nodes = expand_node( node, nodes ) expanded_nodes.extend( nodes )
nodes = expanded_nodes def ids( start, goal, depth=50 ): #
"""Perfoms an iterative depth first search from the start state to the goal. Depth is
optional.""" for i in range( depth ): result = dfs( start, goal, i )
#node_count=node_count+count if result != None: return result def
a_star( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does
not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0,
0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0:
return None # Sort the nodes with custom compare function.
nodes.sort( cmp_a_star ) # take the node from the front of the queue node =
nodes.pop(0) count=count+1 #display_board(node.state) # if this node
is the goal, return the moves it took to get here. #print "Trying state", node.state, "
and move: ", node.operator if node.state == goal: moves = []
temp = node print count, " nodes " while True:
moves.insert( 0, temp.operator ) if temp.depth <=1:
break temp = temp.parent return moves #Expand the
node and add all expansions to the end of the queue nodes.extend(expand_node( node,
nodes ) ) def cmp_a_star( x, y ): # Compare function for A*. f(n) = g(n) + h(n). I use depth
(number of moves) for g(). if (x.depth + h1( x.state, goal_state )) > (y.depth + h( y.state,
goal_state )): return 1 else: return -1 def h1(start,goal):
#Misplaced tiles no_misplaced_tiles = 0 for i in range(1,9): if
start.index(i)!=goal.index(i): no_misplaced_tiles += 1 return
no_misplaced_tiles def h( state, goal ): #Manhattan Distance score = 0 for i
in range( len( state ) ): if state[i] != goal[i]: for j in range(len(state)):
if(state[j] == state[i]): k = j
break diff = i-k if diff < 0: diff = diff *-1
score += diff%3 if diff<6 and diff>2: score = score +
1 if diff>6: score = score + 2 return score
def best_first( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED:
does not work :( nodes = [] count=0 nodes.append( create_node( start, None,
None, 0, 0 ) ) while True: # We've run out of states - no solution. if len(
nodes ) == 0: return None # Sort the nodes with custom compare function.
nodes.sort( cmp_bfs ) # take the node from the front of the queue node =
nodes.pop(0) #display_board(node.state) count=count+1 # if this node
is the goal, return the moves it took to get here. #print "Trying state", node.state, "
and move: ", node.operator if node.state == goal: moves = []
temp = node print count, "nodes" while True:
moves.insert( 0, temp.operator ) if temp.depth <=1:
break temp = temp.parent return moves #Expand the
node and add all expansions to the end of the queue nodes.extend( expand_node( node,
nodes ) ) def cmp_bfs( x, y ): if h(x.state,goal_state) >= h(y.state,goal_state):
return 1 return -1 # Node data structure class Node: def __init__( self, state,
parent, operator, depth, cost ): # Contains the state of the node self.state =
state # Contains the node that generated this node self.parent = parent
# Contains the operation that generated this node from the parent self.operator =
operator # Contains the depth of this node (parent.depth +1) self.depth =
depth # Contains the path cost of this node from depth 0. Not used for depth/breadth
first. self.cost = cost def printpath(directions, starting_state): state = starting_state
display_board(state) print ' ----- ' for d in directions: if d == 'u':
state = move_up(state) if d == 'd': state = move_down(state)
if d == 'l': state = move_left(state) if d == 'r':
state = move_right(state) display_board(state) print ' ----- ' # Main
method def main(): starting_state = [2, 1, 7,8, 6, 0, 3, 4, 5] choice = 5
if choice==1: print "BFS"
result = bfs( starting_state, goal_state ) if choice==2:
print "DFS" result= dfs( starting_state,
goal_state ) if choice==3:
print "IDS" result = ids( starting_state, goal_state )
if choice==4: print "Best First"
result = best_first( starting_state, goal_state ) if choice==5:
print "A star" result = a_star( starting_state, goal_state )
if result == None: print "No solution found"
elif result == [None]: print "Start node was the goal!" else:
printpath(result,starting_state) print len(result), " moves" if __name__ ==
"__main__": main()
Solution
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, 8, 6, 3, 4, 5] import sys global
count def display_board( state ): #print "-------------" print " %i %i %i " %
(state[0], state[3], state[6]) #print "-------------" print " %i %i %i " % (state[1],
state[4], state[7]) #print "-------------" print " %i %i %i " % (state[2], state[5],
state[8]) #print "-------------" def move_up( state ): new_state = state[:] index =
new_state.index( 0 ) if index not in [0, 3, 6]: temp = new_state[index - 1]
new_state[index - 1] = new_state[index] new_state[index] = temp return
new_state else: return None def move_down( state ): new_state = state[:]
index = new_state.index( 0 ) if index not in [2, 5, 8]: temp = new_state[index + 1]
new_state[index + 1] = new_state[index] new_state[index] = temp
return new_state else: return None def move_left( state ): new_state = state[:]
index = new_state.index( 0 ) if index not in [0, 1, 2]: temp = new_state[index
- 3] new_state[index - 3] = new_state[index] new_state[index] = temp
return new_state else: return None def move_right( state ): new_state =
state[:] index = new_state.index( 0 ) if index not in [6, 7, 8]: temp =
new_state[index + 3] new_state[index + 3] = new_state[index]
new_state[index] = temp return new_state else: return None def
create_node( state, parent, operator, depth, cost ): return Node( state, parent, operator,
depth, cost ) def expand_node( node, nodes ): expanded_nodes = []
expanded_nodes.append( create_node( move_up( node.state ), node, "u", node.depth + 1, 0 ) )
expanded_nodes.append( create_node( move_down( node.state ), node, "d", node.depth + 1,
0 ) ) expanded_nodes.append( create_node( move_left( node.state ), node, "l", node.depth
+ 1, 0 ) ) expanded_nodes.append( create_node( move_right( node.state), node, "r",
node.depth + 1, 0 ) ) # Filter the list and remove the nodes that are impossible (move
function returned None) expanded_nodes = [node for node in expanded_nodes if node.state
!= None] #list comprehension! expanded_nodes = [node for node in expanded_nodes if
node not in nodes] #list comprehension! #expanded_nodes = [node for node in
expanded_nodes if node.state!= ((node.parent).parent).state] #list comprehension!
expanded_nodes1 = [] for node in expanded_nodes: temp=node
temp=temp.parent temp=temp.parent if temp==None:
expanded_nodes1.extend(expanded_nodes) break if node.state
!=temp.state: expanded_nodes1.append(node) return
expanded_nodes1 def bfs( start, goal ): nodes = [] count=0 # Create the queue
with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while
True: # We've run out of states, no solution. if len( nodes ) == 0:
return None # take the node from the front of the queue node = nodes.pop(0)
count=count+1 #display_board(node.state) # Append the move we made to
moves # if this node is the goal, return the moves it took to get here. if node.state
== goal: #display_board(node.state) moves = []
temp = node print count, " nodes " while True:
moves.insert(0, temp.operator) if temp.depth == 1:
break temp = temp.parent return moves
# Expand the node and add all the expansions to the front of the stack
#count=count+len(expand_node( node, nodes )) nodes.extend( expand_node( node,
nodes ) ) def dfs( start, goal, depth=12 ): depth_limit = depth # A list (can act as a
stack too) for the nodes. nodes = [] count=0 # Create the queue with the root node
in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've
run out of states, no solution. if len( nodes ) == 0: return None #
take the node from the front of the queue node = nodes.pop(0)
count=count+1; #if this node is the goal, return the moves it took to get here. if
node.state == goal: moves = [] temp = node print
count, " nodes " while True: moves.insert(0, temp.operator)
if temp.depth <= 1: break temp =
temp.parent return moves #,count # Add all the expansions to the beginning
of the stack if we are under the depth limit if node.depth < depth_limit:
expanded_nodes = expand_node( node, nodes ) expanded_nodes.extend( nodes )
nodes = expanded_nodes def ids( start, goal, depth=50 ): #
"""Perfoms an iterative depth first search from the start state to the goal. Depth is
optional.""" for i in range( depth ): result = dfs( start, goal, i )
#node_count=node_count+count if result != None: return result def
a_star( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does
not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0,
0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0:
return None # Sort the nodes with custom compare function.
nodes.sort( cmp_a_star ) # take the node from the front of the queue node =
nodes.pop(0) count=count+1 #display_board(node.state) # if this node
is the goal, return the moves it took to get here. #print "Trying state", node.state, "
and move: ", node.operator if node.state == goal: moves = []
temp = node print count, " nodes " while True:
moves.insert( 0, temp.operator ) if temp.depth <=1:
break temp = temp.parent return moves #Expand the
node and add all expansions to the end of the queue nodes.extend(expand_node( node,
nodes ) ) def cmp_a_star( x, y ): # Compare function for A*. f(n) = g(n) + h(n). I use depth
(number of moves) for g(). if (x.depth + h1( x.state, goal_state )) > (y.depth + h( y.state,
goal_state )): return 1 else: return -1 def h1(start,goal):
#Misplaced tiles no_misplaced_tiles = 0 for i in range(1,9): if
start.index(i)!=goal.index(i): no_misplaced_tiles += 1 return
no_misplaced_tiles def h( state, goal ): #Manhattan Distance score = 0 for i
in range( len( state ) ): if state[i] != goal[i]: for j in range(len(state)):
if(state[j] == state[i]): k = j
break diff = i-k if diff < 0: diff = diff *-1
score += diff%3 if diff<6 and diff>2: score = score +
1 if diff>6: score = score + 2 return score
def best_first( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED:
does not work :( nodes = [] count=0 nodes.append( create_node( start, None,
None, 0, 0 ) ) while True: # We've run out of states - no solution. if len(
nodes ) == 0: return None # Sort the nodes with custom compare function.
nodes.sort( cmp_bfs ) # take the node from the front of the queue node =
nodes.pop(0) #display_board(node.state) count=count+1 # if this node
is the goal, return the moves it took to get here. #print "Trying state", node.state, "
and move: ", node.operator if node.state == goal: moves = []
temp = node print count, "nodes" while True:
moves.insert( 0, temp.operator ) if temp.depth <=1:
break temp = temp.parent return moves #Expand the
node and add all expansions to the end of the queue nodes.extend( expand_node( node,
nodes ) ) def cmp_bfs( x, y ): if h(x.state,goal_state) >= h(y.state,goal_state):
return 1 return -1 # Node data structure class Node: def __init__( self, state,
parent, operator, depth, cost ): # Contains the state of the node self.state =
state # Contains the node that generated this node self.parent = parent
# Contains the operation that generated this node from the parent self.operator =
operator # Contains the depth of this node (parent.depth +1) self.depth =
depth # Contains the path cost of this node from depth 0. Not used for depth/breadth
first. self.cost = cost def printpath(directions, starting_state): state = starting_state
display_board(state) print ' ----- ' for d in directions: if d == 'u':
state = move_up(state) if d == 'd': state = move_down(state)
if d == 'l': state = move_left(state) if d == 'r':
state = move_right(state) display_board(state) print ' ----- ' # Main
method def main(): starting_state = [2, 1, 7,8, 6, 0, 3, 4, 5] choice = 5
if choice==1: print "BFS"
result = bfs( starting_state, goal_state ) if choice==2:
print "DFS" result= dfs( starting_state,
goal_state ) if choice==3:
print "IDS" result = ids( starting_state, goal_state )
if choice==4: print "Best First"
result = best_first( starting_state, goal_state ) if choice==5:
print "A star" result = a_star( starting_state, goal_state )
if result == None: print "No solution found"
elif result == [None]: print "Start node was the goal!" else:
printpath(result,starting_state) print len(result), " moves" if __name__ ==
"__main__": main()

More Related Content

Similar to goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf

import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docxBlake0FxCampbelld
 
Please write a non-recursive procedure to print all nodes for a bina.pdf
Please write a non-recursive procedure to print all nodes for a bina.pdfPlease write a non-recursive procedure to print all nodes for a bina.pdf
Please write a non-recursive procedure to print all nodes for a bina.pdfarcotstarsports
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPaweł Dawczak
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_setskinan keshkeh
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_setskinan keshkeh
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfmail931892
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in ElixirJeff Smith
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
 
Can you fix the errors- It isn't working when I try to run import s.pdf
Can you fix the errors- It isn't working when I try to run    import s.pdfCan you fix the errors- It isn't working when I try to run    import s.pdf
Can you fix the errors- It isn't working when I try to run import s.pdfaksachdevahosymills
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfezonesolutions
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdfkesav24
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdfgulshan16175gs
 

Similar to goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf (20)

import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
 
Please write a non-recursive procedure to print all nodes for a bina.pdf
Please write a non-recursive procedure to print all nodes for a bina.pdfPlease write a non-recursive procedure to print all nodes for a bina.pdf
Please write a non-recursive procedure to print all nodes for a bina.pdf
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Five
FiveFive
Five
 
python codes
python codespython codes
python codes
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in Elixir
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
 
Can you fix the errors- It isn't working when I try to run import s.pdf
Can you fix the errors- It isn't working when I try to run    import s.pdfCan you fix the errors- It isn't working when I try to run    import s.pdf
Can you fix the errors- It isn't working when I try to run import s.pdf
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
 

More from ANJALIENTERPRISES1

H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdf
H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdfH2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdf
H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdfANJALIENTERPRISES1
 
Computer graphics are pictures and movies produced use computers fre.pdf
Computer graphics are pictures and movies produced use computers fre.pdfComputer graphics are pictures and movies produced use computers fre.pdf
Computer graphics are pictures and movies produced use computers fre.pdfANJALIENTERPRISES1
 
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdfCircle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdfANJALIENTERPRISES1
 
C is correct. Only the host that the unicast message is addressed to.pdf
C is correct. Only the host that the unicast message is addressed to.pdfC is correct. Only the host that the unicast message is addressed to.pdf
C is correct. Only the host that the unicast message is addressed to.pdfANJALIENTERPRISES1
 
According to the seriousness level, the following organs areThymu.pdf
According to the seriousness level, the following organs areThymu.pdfAccording to the seriousness level, the following organs areThymu.pdf
According to the seriousness level, the following organs areThymu.pdfANJALIENTERPRISES1
 
Among 40 subjects randomly choose 20 subjects and assign themSol.pdf
Among 40 subjects randomly choose 20 subjects and assign themSol.pdfAmong 40 subjects randomly choose 20 subjects and assign themSol.pdf
Among 40 subjects randomly choose 20 subjects and assign themSol.pdfANJALIENTERPRISES1
 
AdvantagesThe main objective of business combination is to elimina.pdf
AdvantagesThe main objective of business combination is to elimina.pdfAdvantagesThe main objective of business combination is to elimina.pdf
AdvantagesThe main objective of business combination is to elimina.pdfANJALIENTERPRISES1
 
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdf
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdfa. Germ cell speciication in Drosophila is primarily a maternlly con.pdf
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdfANJALIENTERPRISES1
 
A is correct. The packets to be filtered would be heading into the r.pdf
A is correct. The packets to be filtered would be heading into the r.pdfA is correct. The packets to be filtered would be heading into the r.pdf
A is correct. The packets to be filtered would be heading into the r.pdfANJALIENTERPRISES1
 
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdfANJALIENTERPRISES1
 
17-The Y-Chromosome DNA testing helps in the examination of the male.pdf
17-The Y-Chromosome DNA testing helps in the examination of the male.pdf17-The Y-Chromosome DNA testing helps in the examination of the male.pdf
17-The Y-Chromosome DNA testing helps in the examination of the male.pdfANJALIENTERPRISES1
 
#includestdio.h#includestring.h#includestdlib.h#define M.pdf
#includestdio.h#includestring.h#includestdlib.h#define M.pdf#includestdio.h#includestring.h#includestdlib.h#define M.pdf
#includestdio.h#includestring.h#includestdlib.h#define M.pdfANJALIENTERPRISES1
 
The pH and pOH of a solution are defined as pH .pdf
                     The pH and pOH of a solution are defined as  pH .pdf                     The pH and pOH of a solution are defined as  pH .pdf
The pH and pOH of a solution are defined as pH .pdfANJALIENTERPRISES1
 
7 steps are required as 9 is the 7th element and the search is line.pdf
 7 steps are required as 9 is the 7th element and the search is line.pdf 7 steps are required as 9 is the 7th element and the search is line.pdf
7 steps are required as 9 is the 7th element and the search is line.pdfANJALIENTERPRISES1
 
(D) the number of moles of hydroxide ion added and the number of mol.pdf
  (D) the number of moles of hydroxide ion added and the number of mol.pdf  (D) the number of moles of hydroxide ion added and the number of mol.pdf
(D) the number of moles of hydroxide ion added and the number of mol.pdfANJALIENTERPRISES1
 
Look for changes in oxidation numbers. These occ.pdf
                     Look for changes in oxidation numbers.  These occ.pdf                     Look for changes in oxidation numbers.  These occ.pdf
Look for changes in oxidation numbers. These occ.pdfANJALIENTERPRISES1
 
Use Daltons Law of partial pressures. P(Total).pdf
                     Use Daltons Law of partial pressures.  P(Total).pdf                     Use Daltons Law of partial pressures.  P(Total).pdf
Use Daltons Law of partial pressures. P(Total).pdfANJALIENTERPRISES1
 
The Br was originally neutral, but picks up an ex.pdf
                     The Br was originally neutral, but picks up an ex.pdf                     The Br was originally neutral, but picks up an ex.pdf
The Br was originally neutral, but picks up an ex.pdfANJALIENTERPRISES1
 

More from ANJALIENTERPRISES1 (20)

H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdf
H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdfH2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdf
H2SO4 may act as 1) an acidexample 2NaOH + H2SO4 - Na2SO4 +.pdf
 
Computer graphics are pictures and movies produced use computers fre.pdf
Computer graphics are pictures and movies produced use computers fre.pdfComputer graphics are pictures and movies produced use computers fre.pdf
Computer graphics are pictures and movies produced use computers fre.pdf
 
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdfCircle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
 
C is correct. Only the host that the unicast message is addressed to.pdf
C is correct. Only the host that the unicast message is addressed to.pdfC is correct. Only the host that the unicast message is addressed to.pdf
C is correct. Only the host that the unicast message is addressed to.pdf
 
According to the seriousness level, the following organs areThymu.pdf
According to the seriousness level, the following organs areThymu.pdfAccording to the seriousness level, the following organs areThymu.pdf
According to the seriousness level, the following organs areThymu.pdf
 
Among 40 subjects randomly choose 20 subjects and assign themSol.pdf
Among 40 subjects randomly choose 20 subjects and assign themSol.pdfAmong 40 subjects randomly choose 20 subjects and assign themSol.pdf
Among 40 subjects randomly choose 20 subjects and assign themSol.pdf
 
AdvantagesThe main objective of business combination is to elimina.pdf
AdvantagesThe main objective of business combination is to elimina.pdfAdvantagesThe main objective of business combination is to elimina.pdf
AdvantagesThe main objective of business combination is to elimina.pdf
 
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdf
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdfa. Germ cell speciication in Drosophila is primarily a maternlly con.pdf
a. Germ cell speciication in Drosophila is primarily a maternlly con.pdf
 
A is correct. The packets to be filtered would be heading into the r.pdf
A is correct. The packets to be filtered would be heading into the r.pdfA is correct. The packets to be filtered would be heading into the r.pdf
A is correct. The packets to be filtered would be heading into the r.pdf
 
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf
1). A) ipsilateralBelow the point of spinal cord, the nerve paths .pdf
 
-FSolution-F.pdf
-FSolution-F.pdf-FSolution-F.pdf
-FSolution-F.pdf
 
17-The Y-Chromosome DNA testing helps in the examination of the male.pdf
17-The Y-Chromosome DNA testing helps in the examination of the male.pdf17-The Y-Chromosome DNA testing helps in the examination of the male.pdf
17-The Y-Chromosome DNA testing helps in the examination of the male.pdf
 
#includestdio.h#includestring.h#includestdlib.h#define M.pdf
#includestdio.h#includestring.h#includestdlib.h#define M.pdf#includestdio.h#includestring.h#includestdlib.h#define M.pdf
#includestdio.h#includestring.h#includestdlib.h#define M.pdf
 
The pH and pOH of a solution are defined as pH .pdf
                     The pH and pOH of a solution are defined as  pH .pdf                     The pH and pOH of a solution are defined as  pH .pdf
The pH and pOH of a solution are defined as pH .pdf
 
7 steps are required as 9 is the 7th element and the search is line.pdf
 7 steps are required as 9 is the 7th element and the search is line.pdf 7 steps are required as 9 is the 7th element and the search is line.pdf
7 steps are required as 9 is the 7th element and the search is line.pdf
 
(D) the number of moles of hydroxide ion added and the number of mol.pdf
  (D) the number of moles of hydroxide ion added and the number of mol.pdf  (D) the number of moles of hydroxide ion added and the number of mol.pdf
(D) the number of moles of hydroxide ion added and the number of mol.pdf
 
Look for changes in oxidation numbers. These occ.pdf
                     Look for changes in oxidation numbers.  These occ.pdf                     Look for changes in oxidation numbers.  These occ.pdf
Look for changes in oxidation numbers. These occ.pdf
 
D) Insulin .pdf
                     D) Insulin                                       .pdf                     D) Insulin                                       .pdf
D) Insulin .pdf
 
Use Daltons Law of partial pressures. P(Total).pdf
                     Use Daltons Law of partial pressures.  P(Total).pdf                     Use Daltons Law of partial pressures.  P(Total).pdf
Use Daltons Law of partial pressures. P(Total).pdf
 
The Br was originally neutral, but picks up an ex.pdf
                     The Br was originally neutral, but picks up an ex.pdf                     The Br was originally neutral, but picks up an ex.pdf
The Br was originally neutral, but picks up an ex.pdf
 

Recently uploaded

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 

goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf

  • 1. goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, 8, 6, 3, 4, 5] import sys global count def display_board( state ): #print "-------------" print " %i %i %i " % (state[0], state[3], state[6]) #print "-------------" print " %i %i %i " % (state[1], state[4], state[7]) #print "-------------" print " %i %i %i " % (state[2], state[5], state[8]) #print "-------------" def move_up( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [0, 3, 6]: temp = new_state[index - 1] new_state[index - 1] = new_state[index] new_state[index] = temp return new_state else: return None def move_down( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [2, 5, 8]: temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state else: return None def move_left( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [0, 1, 2]: temp = new_state[index - 3] new_state[index - 3] = new_state[index] new_state[index] = temp return new_state else: return None def move_right( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [6, 7, 8]: temp = new_state[index + 3] new_state[index + 3] = new_state[index] new_state[index] = temp return new_state else: return None def create_node( state, parent, operator, depth, cost ): return Node( state, parent, operator, depth, cost ) def expand_node( node, nodes ): expanded_nodes = [] expanded_nodes.append( create_node( move_up( node.state ), node, "u", node.depth + 1, 0 ) ) expanded_nodes.append( create_node( move_down( node.state ), node, "d", node.depth + 1, 0 ) ) expanded_nodes.append( create_node( move_left( node.state ), node, "l", node.depth + 1, 0 ) ) expanded_nodes.append( create_node( move_right( node.state), node, "r", node.depth + 1, 0 ) ) # Filter the list and remove the nodes that are impossible (move function returned None) expanded_nodes = [node for node in expanded_nodes if node.state != None] #list comprehension! expanded_nodes = [node for node in expanded_nodes if node not in nodes] #list comprehension! #expanded_nodes = [node for node in expanded_nodes if node.state!= ((node.parent).parent).state] #list comprehension! expanded_nodes1 = [] for node in expanded_nodes: temp=node temp=temp.parent temp=temp.parent if temp==None: expanded_nodes1.extend(expanded_nodes) break if node.state !=temp.state: expanded_nodes1.append(node) return expanded_nodes1 def bfs( start, goal ): nodes = [] count=0 # Create the queue with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states, no solution. if len( nodes ) == 0: return None # take the node from the front of the queue node = nodes.pop(0)
  • 2. count=count+1 #display_board(node.state) # Append the move we made to moves # if this node is the goal, return the moves it took to get here. if node.state == goal: #display_board(node.state) moves = [] temp = node print count, " nodes " while True: moves.insert(0, temp.operator) if temp.depth == 1: break temp = temp.parent return moves # Expand the node and add all the expansions to the front of the stack #count=count+len(expand_node( node, nodes )) nodes.extend( expand_node( node, nodes ) ) def dfs( start, goal, depth=12 ): depth_limit = depth # A list (can act as a stack too) for the nodes. nodes = [] count=0 # Create the queue with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states, no solution. if len( nodes ) == 0: return None # take the node from the front of the queue node = nodes.pop(0) count=count+1; #if this node is the goal, return the moves it took to get here. if node.state == goal: moves = [] temp = node print count, " nodes " while True: moves.insert(0, temp.operator) if temp.depth <= 1: break temp = temp.parent return moves #,count # Add all the expansions to the beginning of the stack if we are under the depth limit if node.depth < depth_limit: expanded_nodes = expand_node( node, nodes ) expanded_nodes.extend( nodes ) nodes = expanded_nodes def ids( start, goal, depth=50 ): # """Perfoms an iterative depth first search from the start state to the goal. Depth is optional.""" for i in range( depth ): result = dfs( start, goal, i ) #node_count=node_count+count if result != None: return result def a_star( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0: return None # Sort the nodes with custom compare function. nodes.sort( cmp_a_star ) # take the node from the front of the queue node = nodes.pop(0) count=count+1 #display_board(node.state) # if this node is the goal, return the moves it took to get here. #print "Trying state", node.state, " and move: ", node.operator if node.state == goal: moves = [] temp = node print count, " nodes " while True: moves.insert( 0, temp.operator ) if temp.depth <=1: break temp = temp.parent return moves #Expand the node and add all expansions to the end of the queue nodes.extend(expand_node( node,
  • 3. nodes ) ) def cmp_a_star( x, y ): # Compare function for A*. f(n) = g(n) + h(n). I use depth (number of moves) for g(). if (x.depth + h1( x.state, goal_state )) > (y.depth + h( y.state, goal_state )): return 1 else: return -1 def h1(start,goal): #Misplaced tiles no_misplaced_tiles = 0 for i in range(1,9): if start.index(i)!=goal.index(i): no_misplaced_tiles += 1 return no_misplaced_tiles def h( state, goal ): #Manhattan Distance score = 0 for i in range( len( state ) ): if state[i] != goal[i]: for j in range(len(state)): if(state[j] == state[i]): k = j break diff = i-k if diff < 0: diff = diff *-1 score += diff%3 if diff<6 and diff>2: score = score + 1 if diff>6: score = score + 2 return score def best_first( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0: return None # Sort the nodes with custom compare function. nodes.sort( cmp_bfs ) # take the node from the front of the queue node = nodes.pop(0) #display_board(node.state) count=count+1 # if this node is the goal, return the moves it took to get here. #print "Trying state", node.state, " and move: ", node.operator if node.state == goal: moves = [] temp = node print count, "nodes" while True: moves.insert( 0, temp.operator ) if temp.depth <=1: break temp = temp.parent return moves #Expand the node and add all expansions to the end of the queue nodes.extend( expand_node( node, nodes ) ) def cmp_bfs( x, y ): if h(x.state,goal_state) >= h(y.state,goal_state): return 1 return -1 # Node data structure class Node: def __init__( self, state, parent, operator, depth, cost ): # Contains the state of the node self.state = state # Contains the node that generated this node self.parent = parent # Contains the operation that generated this node from the parent self.operator = operator # Contains the depth of this node (parent.depth +1) self.depth = depth # Contains the path cost of this node from depth 0. Not used for depth/breadth first. self.cost = cost def printpath(directions, starting_state): state = starting_state display_board(state) print ' ----- ' for d in directions: if d == 'u': state = move_up(state) if d == 'd': state = move_down(state) if d == 'l': state = move_left(state) if d == 'r': state = move_right(state) display_board(state) print ' ----- ' # Main method def main(): starting_state = [2, 1, 7,8, 6, 0, 3, 4, 5] choice = 5
  • 4. if choice==1: print "BFS" result = bfs( starting_state, goal_state ) if choice==2: print "DFS" result= dfs( starting_state, goal_state ) if choice==3: print "IDS" result = ids( starting_state, goal_state ) if choice==4: print "Best First" result = best_first( starting_state, goal_state ) if choice==5: print "A star" result = a_star( starting_state, goal_state ) if result == None: print "No solution found" elif result == [None]: print "Start node was the goal!" else: printpath(result,starting_state) print len(result), " moves" if __name__ == "__main__": main() Solution goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, 8, 6, 3, 4, 5] import sys global count def display_board( state ): #print "-------------" print " %i %i %i " % (state[0], state[3], state[6]) #print "-------------" print " %i %i %i " % (state[1], state[4], state[7]) #print "-------------" print " %i %i %i " % (state[2], state[5], state[8]) #print "-------------" def move_up( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [0, 3, 6]: temp = new_state[index - 1] new_state[index - 1] = new_state[index] new_state[index] = temp return new_state else: return None def move_down( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [2, 5, 8]: temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state else: return None def move_left( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [0, 1, 2]: temp = new_state[index - 3] new_state[index - 3] = new_state[index] new_state[index] = temp return new_state else: return None def move_right( state ): new_state = state[:] index = new_state.index( 0 ) if index not in [6, 7, 8]: temp = new_state[index + 3] new_state[index + 3] = new_state[index] new_state[index] = temp return new_state else: return None def create_node( state, parent, operator, depth, cost ): return Node( state, parent, operator, depth, cost ) def expand_node( node, nodes ): expanded_nodes = [] expanded_nodes.append( create_node( move_up( node.state ), node, "u", node.depth + 1, 0 ) ) expanded_nodes.append( create_node( move_down( node.state ), node, "d", node.depth + 1, 0 ) ) expanded_nodes.append( create_node( move_left( node.state ), node, "l", node.depth
  • 5. + 1, 0 ) ) expanded_nodes.append( create_node( move_right( node.state), node, "r", node.depth + 1, 0 ) ) # Filter the list and remove the nodes that are impossible (move function returned None) expanded_nodes = [node for node in expanded_nodes if node.state != None] #list comprehension! expanded_nodes = [node for node in expanded_nodes if node not in nodes] #list comprehension! #expanded_nodes = [node for node in expanded_nodes if node.state!= ((node.parent).parent).state] #list comprehension! expanded_nodes1 = [] for node in expanded_nodes: temp=node temp=temp.parent temp=temp.parent if temp==None: expanded_nodes1.extend(expanded_nodes) break if node.state !=temp.state: expanded_nodes1.append(node) return expanded_nodes1 def bfs( start, goal ): nodes = [] count=0 # Create the queue with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states, no solution. if len( nodes ) == 0: return None # take the node from the front of the queue node = nodes.pop(0) count=count+1 #display_board(node.state) # Append the move we made to moves # if this node is the goal, return the moves it took to get here. if node.state == goal: #display_board(node.state) moves = [] temp = node print count, " nodes " while True: moves.insert(0, temp.operator) if temp.depth == 1: break temp = temp.parent return moves # Expand the node and add all the expansions to the front of the stack #count=count+len(expand_node( node, nodes )) nodes.extend( expand_node( node, nodes ) ) def dfs( start, goal, depth=12 ): depth_limit = depth # A list (can act as a stack too) for the nodes. nodes = [] count=0 # Create the queue with the root node in it. nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states, no solution. if len( nodes ) == 0: return None # take the node from the front of the queue node = nodes.pop(0) count=count+1; #if this node is the goal, return the moves it took to get here. if node.state == goal: moves = [] temp = node print count, " nodes " while True: moves.insert(0, temp.operator) if temp.depth <= 1: break temp = temp.parent return moves #,count # Add all the expansions to the beginning of the stack if we are under the depth limit if node.depth < depth_limit: expanded_nodes = expand_node( node, nodes ) expanded_nodes.extend( nodes ) nodes = expanded_nodes def ids( start, goal, depth=50 ): # """Perfoms an iterative depth first search from the start state to the goal. Depth is
  • 6. optional.""" for i in range( depth ): result = dfs( start, goal, i ) #node_count=node_count+count if result != None: return result def a_star( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0: return None # Sort the nodes with custom compare function. nodes.sort( cmp_a_star ) # take the node from the front of the queue node = nodes.pop(0) count=count+1 #display_board(node.state) # if this node is the goal, return the moves it took to get here. #print "Trying state", node.state, " and move: ", node.operator if node.state == goal: moves = [] temp = node print count, " nodes " while True: moves.insert( 0, temp.operator ) if temp.depth <=1: break temp = temp.parent return moves #Expand the node and add all expansions to the end of the queue nodes.extend(expand_node( node, nodes ) ) def cmp_a_star( x, y ): # Compare function for A*. f(n) = g(n) + h(n). I use depth (number of moves) for g(). if (x.depth + h1( x.state, goal_state )) > (y.depth + h( y.state, goal_state )): return 1 else: return -1 def h1(start,goal): #Misplaced tiles no_misplaced_tiles = 0 for i in range(1,9): if start.index(i)!=goal.index(i): no_misplaced_tiles += 1 return no_misplaced_tiles def h( state, goal ): #Manhattan Distance score = 0 for i in range( len( state ) ): if state[i] != goal[i]: for j in range(len(state)): if(state[j] == state[i]): k = j break diff = i-k if diff < 0: diff = diff *-1 score += diff%3 if diff<6 and diff>2: score = score + 1 if diff>6: score = score + 2 return score def best_first( start, goal ): # """Perfoms an A* heuristic search""" # ATTEMPTED: does not work :( nodes = [] count=0 nodes.append( create_node( start, None, None, 0, 0 ) ) while True: # We've run out of states - no solution. if len( nodes ) == 0: return None # Sort the nodes with custom compare function. nodes.sort( cmp_bfs ) # take the node from the front of the queue node = nodes.pop(0) #display_board(node.state) count=count+1 # if this node is the goal, return the moves it took to get here. #print "Trying state", node.state, " and move: ", node.operator if node.state == goal: moves = [] temp = node print count, "nodes" while True: moves.insert( 0, temp.operator ) if temp.depth <=1: break temp = temp.parent return moves #Expand the
  • 7. node and add all expansions to the end of the queue nodes.extend( expand_node( node, nodes ) ) def cmp_bfs( x, y ): if h(x.state,goal_state) >= h(y.state,goal_state): return 1 return -1 # Node data structure class Node: def __init__( self, state, parent, operator, depth, cost ): # Contains the state of the node self.state = state # Contains the node that generated this node self.parent = parent # Contains the operation that generated this node from the parent self.operator = operator # Contains the depth of this node (parent.depth +1) self.depth = depth # Contains the path cost of this node from depth 0. Not used for depth/breadth first. self.cost = cost def printpath(directions, starting_state): state = starting_state display_board(state) print ' ----- ' for d in directions: if d == 'u': state = move_up(state) if d == 'd': state = move_down(state) if d == 'l': state = move_left(state) if d == 'r': state = move_right(state) display_board(state) print ' ----- ' # Main method def main(): starting_state = [2, 1, 7,8, 6, 0, 3, 4, 5] choice = 5 if choice==1: print "BFS" result = bfs( starting_state, goal_state ) if choice==2: print "DFS" result= dfs( starting_state, goal_state ) if choice==3: print "IDS" result = ids( starting_state, goal_state ) if choice==4: print "Best First" result = best_first( starting_state, goal_state ) if choice==5: print "A star" result = a_star( starting_state, goal_state ) if result == None: print "No solution found" elif result == [None]: print "Start node was the goal!" else: printpath(result,starting_state) print len(result), " moves" if __name__ == "__main__": main()