Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain a fixed size heap -python

Tags:

python

h = []
heapq.heappush(h,(10, 1200))
heapq.heappush(h,(20, 31))
heapq.heappush(h,(5, 1))

I want to maintain a fixed heap size of say 3,so when I next have heapq.heappush(h,(3,15)),key with value 20 gets deleted and I am left with values 3,5 and 10.Any ideas how?

like image 474
user2991421 Avatar asked May 25 '15 17:05

user2991421


People also ask

Is the heap a fixed size?

Creating a heap. You can create a fixed-size heap, or a dynamically-sized heap. With a fixed-size heap, the initial block of memory must be large enough to satisfy all allocation requests made to it. With a dynamically-sized heap, the heap can expand and contract as your program needs demand.

What is heap in process?

In certain programming languages including C and Pascal , a heap is an area of pre-reserved computer main storage ( memory ) that a program process can use to store data in some variable amount that won't be known until the program is running.

What is heap CPP?

A heap is a data structure that has the form of a tree and that respects the heap property, namely: every node must be lower than each of its children.


2 Answers

There's no built-in in heapq to check the size, so you'll have to do that yourself:

if len(h) < capacity:
    heapq.heappush(h, thing)
else:
    # Equivalent to a push, then a pop, but faster
    spilled_value = heapq.heappushpop(h, thing)
    do_whatever_with(spilled_value)

Also, note that heapq implements a min heap, not a max heap. You'll need to reverse the order of your priorities, probably by negating them.

like image 128
user2357112 supports Monica Avatar answered Sep 20 '22 15:09

user2357112 supports Monica


I found this post I was trying to implement a top-n heap with fixed size, here is the solution I can offer:

from heapq import heapify, heappush, heappushpop, nlargest

class MaxHeap():
    def __init__(self, top_n):
        self.h = []
        self.length = top_n
        heapify( self.h)
        
    def add(self, element):
        if len(self.h) < self.length:
            heappush(self.h, element)
        else:
            heappushpop(self.h, element)
            
    def getTop(self):
        return sorted(self.h, reverse=True)

and more optimally (thanks to @CyanoKobalamyne)

from heapq import heapify, heappush, heappushpop, nlargest

class MaxHeap():
    def __init__(self, top_n):
        self.h = []
        self.length = top_n
        heapify( self.h)
        
    def add(self, element):
        if len(self.h) < self.length:
            heappush(self.h, element)
        else:
            heappushpop(self.h, element)
            
    def getTop(self):
        return nlargest(self.length, self.h)
like image 25
Learning is a mess Avatar answered Sep 17 '22 15:09

Learning is a mess