Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, how do I make a Priority Queue pop off multiple values of an object?

I have a priority queue of class objects. In my class definition I have:

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

In the event where there are multiple objects that have the same fn value, how do I incorporate a ‘tie breaker’? In other words, something like this:

def __lt__(self, other):
        return self.fn < other.fn and self.gn < other.gn

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add an explicit check for equality between the two fn fields, only checking gn if they’re equal:

def __lt__(self, other):
    if self.fn != other.fn:
        return self.fn < other.fn
    return self.gn < other.gn
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading