Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #101684 > unrolled thread

Re: How to remove item from heap efficiently?

Started byOscar Benjamin <oscar.j.benjamin@gmail.com>
First post2016-01-14 11:53 +0000
Last post2016-01-14 11:53 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: How to remove item from heap efficiently? Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-01-14 11:53 +0000

#101684 — Re: How to remove item from heap efficiently?

FromOscar Benjamin <oscar.j.benjamin@gmail.com>
Date2016-01-14 11:53 +0000
SubjectRe: How to remove item from heap efficiently?
Message-ID<mailman.144.1452772455.13488.python-list@python.org>
On 7 January 2016 at 22:52, Sven R. Kunze <srkunze@mail.de> wrote:
>
> suppose, I need items sorted by two criteria (say timestamp and priority).
> For that purpose, I use two heaps (heapq module):
>
> heapA # items sorted by timestamp
> heapB # items sorted by priority
>
> Now my actual problem. When popping an item of heapA (that's the oldest
> item), I need to remove the very same item from heapB, regardlessly where it
> is in heapB. And vice versa.
>
> Is there a datastructure or a simple trick to achieve that in an efficient
> matter?

Essentially you want a data structure that can efficiently do the following:
1) add an arbitrary item
2) remove an arbitrary item
3) get/pop the minimum element

So Python's set object does add/remove in O(1) but min in O(N). A heap
does add and min in O(log(N)) but remove in O(N). Self-balancing
binary trees can do all of add/remove/min in O(log(N)) so I guess
that's better than what you currently have.

Google shows many third party implementations for Python. Here's one:
https://pypi.python.org/pypi/bintrees/2.0.2

--
Oscar

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web