0

I am using Python 3.8. I have below list:

[['Bangalore', 116.0], ['Mumbai', 132.0], ['Kolkata', 234.0]]

then I have created as a node & added in successors list like this:

successors = [<__main__.Node object at 0x7f89582eb7c0>, <__main__.Node object at 0x7f89582eb790>, <__main__.Node object at 0x7f89582eb7f0>]

I have created a fringe list & adding each successor node. After than sorting it based on distance value. I am getting error - '<' not supported between instances of 'node' and 'node'

for succ_node in successors:
    fringe.append(succ_node)
fringe.sort() <- Error Here

This is my node class:

class Node:
    def __init__(self, parent, name, g):
        self.parent = parent
        self.name = name
        self.g = g

What am I doing wrong?

Tomerikoo
  • 12,112
  • 9
  • 27
  • 37

1 Answers1

3

In python 3 you must define comparison methods for class, for example like below:

class Node:
    def __init__(self, parent, name, g):
        self.parent = parent
        self.name = name
        self.g = g

    def __eq__(self, other):
        return (self.name == other.name) and (self.g == other.g)

    def __ne__(self, other):
        return not (self == other)

    def __lt__(self, other):
        return (self.name < other.name) and (self.g < other.g)

    def __gt__(self, other):
        return (self.name > other.name) and (self.g > other.g)

    def __le__(self, other):
        return (self < other) or (self == other)

    def __ge__(self, other):
        return (self > other) or (self == other)

Sometimes not all these methods are needed - it mainly depends on what kind of comparison you will use.

There is more detailed description: https://portingguide.readthedocs.io/en/latest/comparisons.html

ForceBru
  • 36,993
  • 10
  • 54
  • 78
VillageTech
  • 1,710
  • 4
  • 16