Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: '<' not supported between instances of 'State' and 'State' PYTHON 3

I am trying to utilize a PriorityQueue from the queue class. However, i'm having issues putting custom objects into my PQ. I have implemented the __cmp__ function below:

def __cmp__(self, other):
    return (self.priority > other.priority) - (self.priority < other.priority)

I want the PriorityQueue to be sorted by the priority field, as assigned in my init function:

def __init__(self, board, priority=0):
    self.priority = priority
    # Other logic

However, when I run the code to insert a State object into the PQ, I get this error: TypeError: '<' not supported between instances of 'State' and 'State'

Here is the code that runs the 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))

Where OPEN is the priorityQueue.

Any help would be greatly appreciated... as it should be pretty straightforward to insert a value into a PQ.

like image 978
Varun Vu Avatar asked Apr 18 '17 20:04

Varun Vu


1 Answers

In Python 3 you need to define __lt__ and __eq__ instead of __cmp__.

See https://docs.python.org/3.1/library/stdtypes.html#comparisons.

like image 97
Sean Fujiwara Avatar answered Sep 23 '22 06:09

Sean Fujiwara