pythonstringcomparatorheaplexicographic

Reverse lexicographical using heapq


Essentially I am looking for an efficient way to implement custom comparators using heapq.

For instance x = [('a',5),('c',3),('d',2),('e',1)]

I could heapify it heapq.heapify(x) then pop the min value heapq.heappop(x) which would return ('a', 5). How can I make it such that it returns in reverse lexicographical order ('e', 1)? I know the convention when it comes to numbers is simply multiply the first element of the tuple by -1. Are there simple tricks like that when it comes to strings? I know I could potentially implement a map from a to z ... z to a but it sounds cumbersome.


Solution

  • For numbers you would do something like this:

    import heapq
    
    x = [(1, 5), (3, 3), (4, 2), (5, 1)]
    x = [(-a, b) for a, b in x]
    heapq.heapify(x)
    result = heapq.heappop(x)
    result = (-result[0], result[1])
    

    Similarly, I would do this with letters:

    import heapq
    
    x = [('a',5), ('c',3), ('d',2), ('e',1)]
    x = [(-ord(a), b) for a, b in x]
    heapq.heapify(x)
    result = heapq.heappop(x)
    result = (chr(-result[0]), result[1])
    

    You may want to treat similarly also the second element of each tuple