Skip to content

Instantly share code, notes, and snippets.

@siddhantmedar
Created June 22, 2022 18:59
Show Gist options
  • Save siddhantmedar/45ca7c2ceafc83f9b6895a99fd327000 to your computer and use it in GitHub Desktop.
Save siddhantmedar/45ca7c2ceafc83f9b6895a99fd327000 to your computer and use it in GitHub Desktop.
Custom Comparator for Objects - Heapq
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