我获得了一个实现优先级队列的类,使用函数来评估优先级。
class PriorityQueueWithFunction(PriorityQueue):
"""
Implements a priority queue with the same push/pop signature of the
Queue and the Stack classes. This is designed for drop-in replacement for
those two classes. The caller has to provide a priority function, which
extracts each item's priority.
"""
def __init__(self, priorityFunction):
# type: (object) -> object
"priorityFunction (item) -> priority"
self.priorityFunction = priorityFunction # store the priority function
PriorityQueue.__init__(self) # super-class initializer
def push(self, item):
"Adds an item to the queue with priority from the priority function"
PriorityQueue.push(self, item, self.priorityFunction(item))
我也得到了优先级函数,我将使用。
初始化上面的类def manhattanHeuristic(position, problem, info={}):
"The Manhattan distance heuristic for a PositionSearchProblem"
xy1 = position
xy2 = problem.goal
return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
以上代码已提供给我们,我们无法更改。我必须创建PriorityQueueWithFunction类并将元素推送到它。我的类的 push 函数接受参数,即项目。但我的PriorityFunction需要2。 我应该使用什么样的论据将正确的元素推入我的班级并使我的优先级功能正常工作?
那是我尝试过的,我正在编译错误, manhattanHeuristic ...需要2个参数,1个给定
#Creating a queingFn
queuingFn = PriorityQueueWithFunction(heuristic)
Frontier = queuingFn
#Creating the item that needs to be pushed
StartState = problem.getStartState()
StartNode = (StartState,'',0,(-1,-1))
#Here is my problem
item = StartState , problem
Frontier.push(item)
我应该更改我的项目表格吗?有什么想法吗?
答案 0 :(得分:0)
你应该制作一个包含对曼哈顿的呼叫的新方法:
# for item as dict: item = {'position': POS, 'problem': PROBLEM}
def oneArgHeuristic(item):
position = item.position
problem = item.problem
return manhattanHeuristic(position, problem)
# for item as tuple: item = (POS, PROBLEM)
def oneArgHeuristic(item):
position, problem = item
return manhattanHeuristic(position, problem)
并将其传递给PriorityQueueWithFunction
而不是原来的