0

I have a class person and it has three custom compare functions (compare_by_name / age / height), and i need three priorityQueue(Or Heapq) to save objects seperately using different compare functions? What should I do.

from queue import PriorityQueue

class Person(object):

    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

    def compare_by_name(self):
        # todo

    def compare_by_age(self):
        # todo

    def compare_by_height(self):
        # todo

person1 = Person("Bob", 22, 1.77)
person2 = Person("Ana", 25, 1.70)
person3 = Person("Ceb", 35, 1.88)

q1 = PriorityQueue()
# todo save 3 person and sorted by name
q2 = PriorityQueue()
# todo save 3 person and sorted by age
q3 = PriorityQueue()
# todo save 3 person and sorted by height

I have tried heapq.heappush, but it seems can't save origin object, or will sort by object default comparator at last. And using a data structure list is not acceptable, for i need insert and pop element frequently.

MeetYyj
  • 1
  • 2
  • PriorityQueue's default implementation does not allow for changing how the objects are compared and always use the default comparison function. If you want a custom sorting, you [need to override the comparison functions](https://stackoverflow.com/questions/57898530/custom-comparator-for-building-priorityqueue-in-python) in the object you are comparing. – Shorn Mar 24 '23 at 03:10

0 Answers0