Skip to content Skip to sidebar Skip to footer

Typeerror: '<' Not Supported Between Instances Python

I am solving a problem with genetic algorithm in python 3. I have not completed the full code yet. I test a part of the code whenever I complete it. At present, I am stuck with an

Solution 1:

Given that pre_sorted is a list of lists with items [fitness, part], this croaks whenever comparing two sublists with the same fitness.

Python lists sort lexicographically and are compared element-wise left to right until a mismatching element is found. In your case, the second element (part) is only accessed if the fitness of two parts is the same.

  • [0, part0] < [1, part1] => does not compare part0 and part1 since the fitness is already different.
  • [0, part0] < [0, part1] => does compare part0 and part1 since the fitness is the same.

Suggestion 1

Sort only by fitness: sorted(pre_sorted, key=operator.itemgetter(0))

Suggestion 2

Read the documentation for functools.total_ordering give part a total order:

@total_orderingclasspart():
    [...]

    def__lt__(self, other):
        returnself.number < other.number

And yeah, sorting lists of lists seems wrong. The inner elements might better be tuples, so you cannot accidentally modify the contents.

Solution 2:

So pre_sorted is a list with elements of [int, part]. When you sort this list and have two elements with the same integer value, it then compares the part values to try to determine which goes first. However, since you have no function for determining if a part is less than a part, it throws that error.

Try adding a function __lt__(self, other) to be able to order parts.

More on operators here

Post a Comment for "Typeerror: '<' Not Supported Between Instances Python"