2017-04-18 73 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您可以修改已在队列中的项目的优先级,并可能观察到意外的行为。

在第二种方法中,这不是问题,因为元组是不可变的。

相关问题