我想从队列类中使用PriorityQueue。但是,我遇到了将自定义对象放入我的PQ的问题。我已经实现以下__cmp__
功能:TypeError:'状态'和'状态'的实例之间不支持'<'PYTHON 3
def __cmp__(self, other):
return (self.priority > other.priority) - (self.priority < other.priority)
我想时Queue由优先级字段进行排序,在我的初始化函数分配:
def __init__(self, board, priority=0):
self.priority = priority
# Other logic
然而,当我运行代码插入一个国家对象进入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。
'__cmp__'在Python 3中不是一个特殊的方法名称。试着定义'__lt__'来查看它是否有效。 – iafisher