Skip to content

Position of element in queue #31

Answered by nvictus
jonathan-s asked this question in Q&A
Discussion options

You must be logged in to vote

By finding the relative position, I'm taking that to mean finding the rank of an element among all other elements in the queue. That's an interesting problem!

Because it's implemented as a heap, the most naive solution would be to enumerate and pop elements out of the heap until we run into the key we are looking for. Basically, something equivalent to:

rank = next(dropwhile(lambda x: x[1] != key, enumerate(pq.copy().popkeys())))[0]

Since that operation is destructive, we make a copy of the queue first. Copying aside, as described in this blog post, should be O(k log(n)), where k is the rank of the element.

I'm not sure if using nlargest or nsmallest as you suggested would help in general…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by nvictus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #4 on September 08, 2024 18:31.