handling tie breakers with heapq in python

37 Views Asked by At

I have this array

values = [("aaa", 10), ("bbb", 10), ("ccc", 10), ("David", 15)]

I want to add these to a priorityqueue. For each value, I want to sort by value[1] (the number) then if its a tie (e.g ("aaa", 10), ("bbb", 10)), I want to sort lexigraphically by value[0] (the string)

I have tried doing this

def compareValAndName(a, b):
    if a[1] == b[1]:
        if a[0] < b[0]:
            return 1
        else:
            return -1
    return a[1] - b[1]
    
n_largest = heapq.nlargest(5, values, key=cmp_to_key(compareValAndName))

However, I don't want to use largest since I will be popping and pushing into my queue consistantly

0

There are 0 best solutions below