Added A* puzzle exercise.
3 Author: Eugen Sawin <sawine@informatik.uni-freiburg.de>
14 print "heuristic: none"
15 search(init, goal, Heuristic(goal))
16 print "\nheuristic: misplaced tiles"
17 search(init, goal, MisplacedTiles(goal))
18 print "\nheuristic: manhattan distance"
19 search(init, goal, ManhattanDist(goal))
21 def search(init, goal, h):
25 heapq.heapify(frontier)
26 node = Node(init, None, 0, 0)
27 heapq.heappush(frontier, (0, node))
30 k, node = heapq.heappop(frontier)
32 explored.add(node.state)
33 if node.state == goal:
34 print "goal found in %i steps" % len(explored)
36 for child in expand(node, h):
39 heapq.heappush(frontier, (child.h_cost, child))
43 state = list(node.state)
52 for i, v in enumerate(node.state):
56 children.append(Node(s, node, cost, h(s) + 1))
59 children.append(Node(s, node, cost, h(s) + 1))
62 children.append(Node(s, node, cost, h(s) + 1))
65 children.append(Node(s, node, cost, h(s) + 1))
69 def __init__(self, state, parent, cost, h_cost):
74 def __less__(self, node):
75 return self.h_cost < node.h_cost
77 return "\n".join((str(self.state[:3]),
81 class Heuristic(object):
82 def __init__(self, goal):
84 def __call__(self, state):
87 class MisplacedTiles(Heuristic):
88 def __call__(self, state):
90 for i, s in enumerate(state):
95 class ManhattanDist(Heuristic):
96 def __call__(self, state):
98 for i, s in enumerate(state):
99 for i2, s2 in enumerate(self.goal):
105 from argparse import ArgumentParser
107 def parse_arguments():
108 parser = ArgumentParser(description="8 puzzle")
109 return parser.parse_args()
111 if __name__ == "__main__":