我正在尝试使用队列类中的 PriorityQueue。但是,我在将自定义对象放入我的 PQ 时遇到了问题。我已经实现了 __cmp__
功能如下:
def __cmp__(self, other):
return (self.priority > other.priority) - (self.priority < other.priority)
我希望 PriorityQueue 按优先级字段排序,如我的 init 函数中分配的那样:
def __init__(self, board, priority=0):
self.priority = priority
# Other logic
但是,当我运行将 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))
其中 OPEN 是 priorityQueue。
任何帮助将不胜感激...因为将值插入 PQ 应该非常简单。
最佳答案
在 Python 3 中,您需要定义 __lt__
和 __eq__
而不是 __cmp__
。
参见 https://docs.python.org/3.1/library/stdtypes.html#comparisons .
关于python - 类型错误 : '<' not supported between instances of 'State' and 'State' PYTHON 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481158/