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 ?
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[0] for x in heap if x[1] == node]))
OUTPUT:
The Distance of the node 4 is [321]
OR:
print("The Distance of the node {} is {}".format(node, str([x[0] for x in heap if x[1] == node]).strip("[]")))
OUTPUT:
The Distance of the node 4 is 321