# how checking if there is a value in a heapq

harry

I am working heapq package in order to work with graphs.

Let's suppose a list " heap ", filed by 2 tuples a and b representing ( distance, node )

``````import heapq

heap = []
a = (321,4)
b = (258,3)
heapq.heappush(heap,a)
heapq.heappush(heap,b)
``````

Is there any way to check if node 4 is in the heap list ? and if yes, how can I get its distance ?

DirtyBit

Using `any`:

``````import heapq

heap = []
a = (321,4)
b = (258,3)
heapq.heappush(heap,a)
heapq.heappush(heap,b)
node = 4
if any(node in d for d in heap):
print("The Distance of the node {} is {}".format(node, [x for x in heap if x == node]))
``````

OUTPUT:

``````The Distance of the node 4 is 
``````

OR:

``````print("The Distance of the node {} is {}".format(node, str([x for x in heap if x == node]).strip("[]")))
``````

OUTPUT:

``````The Distance of the node 4 is 321
``````

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at

0 comments
Login to comment