Harry Logsdon
Harry Logsdon

Reputation: 93

Accessing indexs and length of a heapq?

I originally tried writing an algorithm to solve a 15-puzzle using a priority queue, but my instructor told us that we were required to write in an a* implementation, and recommended that we use a heapq instead of a priority queue. I'm having trouble finding the length/size of my heapq, and accessing elements of my heapq. I was under the impression that by using a heapq you would be able to access elements in the heapq that you would not be able to access in a priority queue. However, there don't seem to be any methods for finding the length/retrieving elements from a heapq. Do any of you know of a way to get the length/element of a heapq or a better suited data structure for this situation?

Upvotes: 7

Views: 20456

Answers (1)

loxaxs
loxaxs

Reputation: 2289

heapq heaps are nothing more than lists whose elements respect a special (non-unique) order.

You can use len(heap) on it just like you would on any other list.

In [1]: import heapq
In [2]: heap = [40, 10, 20, 30]
In [3]: heapq.heapify(heap)
In [4]: heap
Out[4]: [10, 30, 20, 40]

In [5]: heapq.heappop(heap)
Out[5]: 10

In [6]: heap
Out[6]: [20, 30, 40]

In [7]: len(heap)
Out[7]: 3

You should also read the python documentation for heapq: the example section should interest you.

Upvotes: 15

Related Questions