4️⃣

13.4 Comparison Operators

Comparison Operators

Finally, there are comparison operators. These operators share a similar input signature as mathematical operations, but it must be known that the other argument these methods are inputted are also the same class type (otherwise, it won’t make sense).

Below is a list of operators

  • __lt__ - implements the less than operator (<)
  • __gt__ - implements the greater than operator (>)
  • __le__ - implements the less than or equal to operator (<=)
  • __ge__ - implements the greater than or equal to operator (>=)
  • __eq__ - implements the equals operator (==)
  • __ne__ - implements the not equals operator (!=)

In this example, our operators will compare the vectors based on the magnitude of the vectors. It will not use lexicographical ordering. There are many ways to calculate the magnitude of the vectors, but we will be using the Euclidean or L2 norm: the square root of all the vector elements squared.

class Vector:

    def __init__(self, vals):
				"""
		    Constructor
		    self: a reference to the object we are creating
		    vals: a list of integers which are the contents of our vector
		    """
        self.vals = vals
        # print("Assigned values ", vals, " to vector.")

    def __str__(self):
				"""
		    String Function
		    Converts the object to a string in readable format for programmers
		    """
        return str(self.vals)

    def __pow__(self, power):
        return Vector([i ** power for i in self.vals])

    # Calculates Euclidean norm
    def norm(self):
        return sum((self ** 2).vals) ** 0.5

    # __lt__:  implements the less than operator (<)
    def __lt__(self, other):
        return self.norm() < other.norm()

    # __gt__: implements the greater than operator (>)
    def __gt__(self, other):
        return self.norm() > other.norm()

    # __le__: implements the less than equal to operator (<=)
    def __le__(self, other):
        return self.norm() <= other.norm()

    # __ge__: implements the greater than equal to operator (>=)
    def __ge__(self, other):
        return self.norm() >= other.norm()

    # __eq__: implements the equals operator (==)
    def __eq__(self, other):
        return self.norm() == other.norm()

    # __ne__:implements the not equals operator (!=)
    def __ne__(self, other):
        return self.norm() != other.norm()


vec = Vector([2, 3, 2])
vec2 = Vector([3, 4, 5])
print(vec < vec2)  # True
print(vec > vec2)  # False

print(vec <= vec2)  # True
print(vec >= vec2)  # False
print(vec <= vec)  # True
print(vec >= vec)  # True

print(vec == vec2)  # False
print(vec == vec)  # True

print(vec != vec2)  # True
print(vec != vec)  # False

View code on GitHub.

Practice

Matrix Less Greater

Have your teacher walk you through this one

Implement the less than and greater than operators for the Matrix class(from a previous example problem) so that we compare them based on their Frobenius norms which we have implemented in the earlier section as an exercise. Also, the unmodified Matrix class code will be given.

Lexicographical Vector

Reimplement the __lt__ and __gt__ in the given Vector class (the one in this section) so that we are comparing the vector’s contents based on lexicographical ordering. Think of lexicographical ordering as how you arrange words in a dictionary. For instance, by lexicographical ordering, ‘a’ < ‘ab’, ‘ab’ < ‘ad’, ‘bcd’ > ‘a’. It works analogously for numbers, but instead, each character has been substituted by a number.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.