Created
June 22, 2022 18:59
-
-
Save siddhantmedar/45ca7c2ceafc83f9b6895a99fd327000 to your computer and use it in GitHub Desktop.
Custom Comparator for Objects - Heapq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
from collections import Counter | |
class Obj: | |
def __init__(self, a, b): | |
self.a = a | |
self.b = b | |
def __lt__(self, other): | |
if self.a < other.a: | |
return True | |
elif self.a > other.a: | |
return False | |
elif self.b < other.b: | |
return True | |
elif self.b > other.b: | |
return False | |
def __gt__(self, other): | |
if self.a > other.a: | |
return True | |
elif self.a > other.a: | |
return False | |
elif self.b > other.b: | |
return True | |
elif self.b < other.b: | |
return False | |
def __eq__(self, other): | |
return self.a == other.b and self.b == other.b | |
nums = [1, 1, 2, 2, 111] | |
lst = [] | |
mp = Counter(nums) | |
for k, v in mp.items(): | |
heapq.heappush(lst, Obj(v, k)) | |
while lst: | |
print(heapq.heappop(lst).__dict__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment