Implementing a max heap in python using heapq for a custom class object with custom comparators in Python?

47 views Asked by At

Python's heapq seems to only support min heaps. If the heap were just made of numbers or an object thats compared using numbers, you could simply multiple each number by -1 to create a max heap but how would this work for more custom objects?

Say I had a student class where I can sort students by their names in alphabetical order:

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def __repr__(self):
        return f"Student(name='{self.name}', age={self.age}, grade='{self.grade}')"

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

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

# List of students
students = [
    Student("Alice", 20, "A"),
    Student("Bob", 19, "B"),
    Student("Charlie", 21, "C"),
]

I can create a min heap by just doing:

heapq.heapify(students)
print("Min Heap (List representation):")
print(students)

By how would I make a max heap out of this list? I guess I could flip the equality in __lt__ but I'm not really fond of that idea.

This feels a hacky solution, I'd prefer a more elegant one if possible

0

There are 0 answers