heihei
heihei

Reputation: 3

python- Type Error: '<' between instances of Node and Node

i'm new to python and i'm having this error and i tried several things to solve it but i couldn't find any that's working

Type Error: '<' between instances of Node and Node

Upvotes: 0

Views: 72

Answers (1)

Hara Chaitanya
Hara Chaitanya

Reputation: 998

You need to write special methods for comparison. heapq will internally perform comparisons on elements being added to the heap, your code fails since the element being added is an object and object by default cannot perform comparisons.

We need to define Special methods __lt__ (<) or __gt__ (>) in order to compare two objects.

For example in your program,, you can add __lt__ method under class Node like below, to compare on freq property of class Node.

def __lt__(self, other):
    return self.freq < other.freq

Now, you can perform < comparisons on objects, similarly you can write for >, >=, <= or == comparisons as well.

Upvotes: 1

Related Questions