medium +20 pts

Comparable mixin

Implement a Comparable mixin that adds rich comparison operators to any class with __lt__.

Implement a mixin class `Comparable` that, when subclassed together with a class defining `__lt__`, automatically provides the remaining comparison methods (`__le__`, `__gt__`, `__ge__`, `__eq__`, `__ne__`) based on that `__lt__` method. The mixin must work for any classes that define `__lt__` (and may also define `__eq__` if needed). Your task is to define the class `Comparable` with the following methods: - `__le__(self, other)`: return `self < other or self == other` - `__gt__(self, other)`: return `not (self < other or self == other)` - `__ge__(self, other)`: return `not (self < other)` - `__eq__(self, other)`: return `not (self < other or other < self)` - `__ne__(self, other)`: return `not (self == other)` These methods should work only with objects of the same type (or subclass). If `other` is not an instance of the same class as `self` (including instances of unrelated classes), raise `NotImplementedError`. You are not allowed to use `functools.total_ordering` in your implementation. The mixin is intended to be used like: ```python class Person(Comparable): def __init__(self, name, age): self.name = name self.age = age def __lt__(self, other): if not isinstance(other, Person): raise NotImplementedError return self.age < other.age ``` Then all comparison operators work: `p1 < p2`, `p1 <= p2`, `p1 > p2`, `p1 >= p2`, `p1 == p2`, `p1 != p2`. Write the class `Comparable` as defined above. Ensure all methods work correctly and pass the provided tests.

Constraints

- The `Comparable` class must not use any external libraries. - All comparison methods must return a boolean or raise `NotImplementedError` for incompatible types. - Input objects will be of the same class when compared in tests. - Time complexity: O(1) per operation (assuming `__lt__` is O(1)).

Example

>>> class Person(Comparable):
...     def __init__(self, age): self.age = age
...     def __lt__(self, other):
...         if not isinstance(other, Person): raise NotImplementedError
...         return self.age < other.age
>>> p1, p2 = Person(30), Person(25)
>>> p1 > p2
True
>>> p1 >= p2
True
>>> p1 <= p2
False
>>> p1 == p2
False
>>> p1 != p2
True
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

In each method, first check type compatibility with `isinstance(other, type(self))` and raise `NotImplementedError` if false.
For `__eq__`, use `not (self < other or other < self)` to avoid recursion.
For `__ne__`, use `not (self == other)` to avoid recursion.
Remember that the methods defined in the mixin are inherited by subclasses.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.