2017-04-18 28 views
1

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

+0

'__cmp__'在Python 3中不是一個特殊的方法名稱。試着定義'__lt__'來查看它是否有效。 – iafisher

回答

1

相反的__cmp__你需要實現__lt__之一,__le____gt__,或__ge__方法和使用functools.total_ordering裝飾

functools.total_ordering(cls) Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __lt__() , __le__() , __gt__() , or __ge__() . In addition, the class should supply an __eq__() method.

然而,較好地解決了將被放在一個元組(priority, state_object)進入隊列,因爲他們在文檔中建議PriorityQueue

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]) . A typical pattern for entries is a tuple in the form: (priority_number, data) .

第一種方法的缺陷是t您可以修改已在隊列中的項目的優先級,並可能觀察到意外的行爲。

在第二種方法中,這不是問題,因爲元組是不可變的。

相關問題