我想從隊列類中使用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