我正在尝试利用队列类中的 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 是优先级队列。
任何帮助将不胜感激...因为将值插入 PQ 应该非常简单。
在Python 3中你需要定义__lt__
and __eq__
代替__cmp__
.
See https://docs.python.org/3.1/library/stdtypes.html#comparisons https://docs.python.org/3.1/library/stdtypes.html#comparisons.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)