2

I am trying to implement HeapQ using Python but im stuck with this scenario , where i need to get the position of the key in the queue ? . I hit the wall trying to solve this. Any tips will be appreciated.

Harun Guna
  • 129
  • 1
  • 1
  • 7

2 Answers2

0

Python builtin heapq implements a min heap. So, if your key is minimum then index of the key is zero. If you want to find index of any other element just use the index method in the list. See the below code for example.

import heapq
numbers = [1, 11, 2, 5, 3, 9, 6]

heap = [] # a list which will be used as heap

for number in numbers:
    heapq.heappush(heap, number)

# heapq is min heap. The minimum element will be at the root or index 0.
# The following line will print 1 as it is the minimum in the list.
print(heap[0]) 

# To find a element index just use the index function on the list
print(heap.index(11))
avijit
  • 805
  • 2
  • 12
  • 21
0

Binary heaps, by default, do not provide an easy way to find the position of an element in the heap. If you need to do this, the most common (and probably most efficient?) strategy is to maintain an auxiliary table alongside the binary heap mapping each item to its index in the heap. Then, whenever the binary heap swaps two elements, it updates the table to reflect that the positions of those elements have changed.

Unfortunately, there isn’t an easy way to add this functionality to an existing priority queue implementation given in a library. You may have to implement your own binary heap from scratch in order to do this.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065