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 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)=='1': 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)=='1': return cur if not (cur.state in expanded 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) - 'print' has been replaced with 'print()' - Condition for the if statements on line#39,49 is specified more explicitly, for goalp(cur) returns a char type value (character '0' is also considered as true) - 'expanded.has_key(cur.state)' on line#51 has been removed, since the function is deprecated - Note that the initialization on line#45 ('expanded = {}') is still valid """