我有两个类PriorityQueue
和PriorityQueueWithFunction
,不能以任何方式更改,定义为:
class PriorityQueue:
def __init__(self):
self.heap = []
self.count = 0
def push(self, item, priority):
entry = (priority, self.count, item)
heapq.heappush(self.heap, entry)
self.count += 1
def pop(self):
(_, _, item) = heapq.heappop(self.heap)
return item
def isEmpty(self):
return len(self.heap) == 0
class PriorityQueueWithFunction(PriorityQueue):
def __init__(self, priorityFunction):
self.priorityFunction = priorityFunction
PriorityQueue.__init__(self) # super-class initializer
我已经实现了一个使用PriorityQueueWithFunction
类的A * Search算法。它需要两个参数。第一个是problem
,它是搜索问题的抽象表示,其具有SearchAgent和Goal所在的起始状态。第二个参数是已经可以接受的 heuristic
。这是我的实施:
def aStarSearch(problem, heuristic):
closed = set() # A set to implement GraphSearch for efficiency
# Two variables so that the passed function can recognize argument types before
# they've been called
node = problem.getStartState()
cost = 0
# Instantiate the real fringe. The function is cost + heuristic value
fringe = PriorityQueueWithFunction(lambda x: cost + heuristic(node, problem))
fringe.push((problem.getStartState(), 0, [])) # The first state with no cost or action
while not fringe.isEmpty():
node, cost, directions = fringe.pop()
if problem.isGoalState(node):
return directions
if not (node in closed):
closed.add(node)
# getSuccessors(state) method expands all child nodes of node
for node, direction, costOfStep in problem.getSuccessors(node):
fringe.push((node, cost + costOfStep, directions + [direction]))
if fringe.isEmpty():
print "No solution was found."
return []
我已经多次检查过这个实现,如果可能的话,它确实每次都找到了目标解决方案路径,但它找不到目标解决方案最佳。
我已经调试了这个问题,结果发现PriorityQueueWithFunction
不像PriorityQueue
那样。它取出了"第一个"而不是具有最低优先级整数的条目。
谁能告诉我这里有什么问题?我的实施会如何使我的PriorityQueueWithFunction
行为好像是Queue
而不是PriorityQueue
?