import string class Node: def __init__ (self,state): self.state = state def makeNodes(n,states): return [Node(s) for s in states] def successors(node): """ return a list of all legal successor states of node.state""" print "Enter successors of ", node.state, "(in a list) ", return raw_input(" --> ") def goalp(node): """ return 1 if node.state is a goal; 0 otherwise.""" print "Is ", node.state, "a goal (0 for no, 1 for yes)", x = input("? ") return x def treesearch(qfun, fringe): while fringe: cur = fringe[0] fringe = fringe[1:] if goalp(cur): return cur fringe = qfun(makeNodes(cur,successors(cur)), fringe) return [] def graphsearch(qfun, fringe): expanded = {} while fringe: cur = fringe[0] fringe = fringe[1:] if goalp(cur): return cur if not (expanded.has_key(cur.state) and\ expanded[cur.state].gval <= cur.gval): expanded[cur.state] = cur fringe = qfun(makeNodes(cur,successors(cur)), fringe) return [] def myappend(list1, list2): return list1 + list2 def prepend(list1, list2): return list2 + list1 def depthfirstsearch(start): return treesearch (myappend, [Node(start)]) def depthfirstsearch1(start): return graphsearch (myappend, [Node(start)]) def breadthfirstsearch(start): return treesearch (prepend, [Node(start)]) def bestfirstsearch(start): """ Called greedy best-first search in Russell & Norvig 2nd edition""" return treesearch(mysort,[Node(start)]) def comparestates(state1,state2): return cmp(h(state1),h(state2)) def mysort (list1, list2): total = list1 + list2 total.sort(comparestates) return total print "Let's start with breadth first search:" result = breadthfirstsearch("a") if result == []: print result else: print result.state print "Now depth first search, checking for repeated states:" result = depthfirstsearch1("a") if result == []: print result else: print result.state """ CHANGELOG (08/30/2013: ported by charmgil) - line#26: input() has been replaced with raw_input() """