Looking for inverted heap in python

I would like to comb n the biggest extremes of the timers. heapq works great for the smallest

def nlargest(series, n):
    count = 0
    heap = []
    for e in series:
        if count < n:
            count+=1
            hp.heappush(heap, e)
        else:
            # keeps heap size fixed 
            hp.heappushpop(heap,e)  
    ''' note: heap[0] is smallest '''
    return heap

but what about n smallest? Note that I want a subset of the original series, so the heapify and reverseing order will not work. I would essentially like to overload the comparison operator from gt to lt. Not very familiar with overloading in python.

A less attractive option would be (assuming numerical values) would be to deny the item before inserting and then deny the whole bunch of returns (return the list or drag the list with negation), but this seems kludgy, and it no longer works for non-numeric ones have gt and lt. Any nifty solutions?

0
source share
2 answers

"" , -1.

, nsmallest , "" , :

def nsmallest(series, n, invert=lambda x: -1 * x):
    count = 0
    heap = []
    for e in series:
        if count < n:
            count += 1
            hp.heappush(heap, (invert(e), e))
        else:
            # keeps heap size fixed
            hp.heappushpop(heap, (invert(e), e))  
    # note: heap[0][1] is largest, remove inverted priorities
    return [h[1] for h in heap]

, (invertedpriority, value), .

, , , - - :

alphanumeric_invert = lambda x: [(ord(c) * -1) for c in x] 
+3

heapq.nsmallest Python:

heapq.nsmallest(n, iterable[, key])

n , iterable. : sorted(iterable, key=key)[:n]

0

All Articles