Var*_* Vu 1 python priority-queue python-3.x
我正在尝试使用队列类中的PriorityQueue.但是,我在将自定义对象放入PQ时遇到问题.我已经实现了__cmp__以下功能:
def __cmp__(self, other):
return (self.priority > other.priority) - (self.priority < other.priority)
Run Code Online (Sandbox Code Playgroud)
我希望PriorityQueue按优先级字段排序,在init函数中指定:
def __init__(self, board, priority=0):
self.priority = priority
# Other logic
Run Code Online (Sandbox Code Playgroud)
但是,当我运行代码将一个State对象插入PQ时,我收到此错误: TypeError: '<' not supported between instances of 'State' and 'State'
这是运行PQ的代码.
if op.precond(S):
new_state = op.state_transf(S)
if not (OPEN.queue.__contains__(new_state)) and not (new_state in CLOSED):
GVALUES[Problem.hash(new_state)] = get_distance_value(op, new_state)
HEUR_VALUES[Problem.hash(new_state)] = get_AStar_value(new_state)
print("NEW STATE: " + str(new_state))
OPEN.put(new_state)
print("OPEN: " + str(OPEN.queue))
Run Code Online (Sandbox Code Playgroud)
其中OPEN是priorityQueue.
任何帮助都将非常感谢...因为将值插入PQ应该非常简单.
在Python 3中,您需要定义__lt__而__eq__不是__cmp__.
请参阅https://docs.python.org/3.1/library/stdtypes.html#comparisons.
而不是__cmp__您需要实现__lt__, __le__, __gt__, 或__ge__方法之一并使用 functools.total_ordering装饰器
functools.total_ordering(cls)给定一个定义一个或多个丰富的比较排序方法的类,这个类装饰器提供其余的。这简化了指定所有可能的丰富比较操作所涉及的工作:这个类必须定义之一
__lt__(),__le__(),__gt__(),或__ge__()。此外,该类应该提供一个__eq__()方法。
但是,更好的解决方案是将元组(priority, state_object)放入队列中,正如他们在文档中建议的那样PriorityQueue
首先检索最低值的条目(最低值的条目是由 返回的
sorted(list(entries))[0])条目。条目的典型模式是以下形式的元组:(priority_number, data).
第一种方法的缺陷是您可以修改已经在队列中的项目的优先级,并可能观察到意外行为。
在第二种方法中,这不是问题,因为元组是不可变的。
| 归档时间: |
|
| 查看次数: |
3897 次 |
| 最近记录: |