Responding to Stefan Musarra, his approach works well.
This seems like a good approach for making a max heap in general:
from heapq import heapify, heappop as pop, heappush as push nums = [5, -6, 20, -3, 5, 0, 12, 5] # Reverse comparison to simulate a max heap class Num(int): def __lt__(self, other_num): return self > other_num # Heapify max_heap = [Num(num) for num in nums] heapify(max_heap) # Pushing and popping for n in [-5, 6, 3, 10, -4, 3, -6, 7, 8]: push(max_heap, Num(n)) for _ in range(len(max_heap)): print(pop(max_heap))
Output:
20 12 10 8 7 6 5 5 5 3 3 0 -3 -4 -5 -6 -6
It works for strings as well:
names = ['sarah', 'david', 'zack', 'xavier', 'carlos', 'alice', 'ethan', 'fred'] class Str(str): def __lt__(self, other): return self > other max_heap = [Str(name) for name in names] heapify(max_heap) for name in ['bob', 'rick', 'oscar', 'yasmin', 'george', 'peter']: push(max_heap, Str(name)) for _ in range(len(max_heap)): p = pop(max_heap) # p is of type 'Str', it can be converted back with str(p) print(p)
Output:
zack yasmin xavier sarah rick peter oscar george fred ethan david carlos bob alice
I noticed that the elements come out in their wrapper class still, but can be converted back with int() or str()