Hi @ericvsmith,
Suppose you’re solving a Dijkstra’s algorithm problem and need to use a priority queue. Currently, in Python, you might implement it like this:
import heapq
reference_point = (0, 0)
def squared_distance(point):
x0, y0 = reference_point
return (point[0] - x0) ** 2 + (point[1] - y0) ** 2
heap = []
points = [(1, 2), (3, 4), (-1, -1), (0, 0), (2, -2)]
for point in points:
distance = squared_distance(point)
heapq.heappush(heap, (distance, point))
Suppose, I’ve made changes to the Python implementation of heapq module to allow using a custom comparator function. Now, you can write:
import heapq
reference_point = (0, 0)
def point_comparator(p1, p2):
x0, y0 = reference_point
d1 = (p1[0] - x0) ** 2 + (p1[1] - y0) ** 2
d2 = (p2[0] - x0) ** 2 + (p2[1] - y0) ** 2
return (d1 > d2) - (d1 < d2)
heap = []
points = [(1, 2), (3, 4), (-1, -1), (0, 0), (2, -2)]
for point in points:
heapq.heappush(heap, point, comparator=point_comparator)
The latter is very intuitive, and most language containers implementing priority_queue
provide a way to pass a comparator function.
I understand that there are many open-source packages offering various implementations in different styles—functional, object-oriented, or other paradigms—but in coding competitions and interview settings, people are often not allowed to use these packages.
yes @Alex-Wasowicz ,I also didn’t find any request. I think we can agree that most competitive programmers use C++, and those who use Python have adapted their approaches accordingly, often starting from high school.
In response to @chepner , yes, the first thing that came to mind was to create an object and define the lt and other comparison methods. However, why should we use an object that takes extra memory when we can use a tuple?
Should I create a ticket for this? I was planning to post a new question about adding an optional comparator to heapq.