0

Want to get the minimal elements for a min heap in Python using heapq, here is my code and wondering if using h[0] is the correct way or a more elegant public API for heapq? I tried to find is there is an API to get minimal element of a heap, but cannot find it out.

BTW, using Python 2.

import heapq

def heapMin(iterable):
   h = []
   for value in iterable:
       heapq.heappush(h, value)
   return h[0]

if __name__ == "__main__":

   print heapMin([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])

thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 2
    Maybe `heapq.nsmallest(1, h)`? – vaultah Dec 06 '15 at 08:29
  • 1
    Not sure why `h[0]` is not elegant for you. Even docs mention it https://docs.python.org/2/library/heapq.html#heapq.heappop – Konstantin Dec 06 '15 at 08:30
  • 1
    @vaultah it seems that this will do unnecessary work. See https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l221 – Konstantin Dec 06 '15 at 08:34
  • @Alik, what specific unnecessary work do you mean? – Lin Ma Dec 07 '15 at 06:00
  • @Alik, thanks for pointing out the document and if you could add a reply, I will mark it as an Answer to benefit other people. :) – Lin Ma Dec 07 '15 at 06:01
  • 1
    @LinMa `heapq.nsmallest(1, h)` performs a lot of work internally. Take a look at sources of `heapq` module I've referenced earlier. It doesn't make sense to use it if `h` was already heapified – Konstantin Dec 07 '15 at 09:13
  • @Alik, thanks a lot. Would you add a reply, I will mark it as answered to benefit other people. Thanks. :) – Lin Ma Dec 08 '15 at 01:31

1 Answers1

1

Convert your iterable list into a heap in one go, use this. Instead of looping, use the heapify() function and the heappop(iterable) should return you the first index (least number)

heapq.heapify(iterable)
print heapq.heappop(iterable)
sameera sy
  • 1,708
  • 13
  • 19