Skip to main content

No project description provided

Project description

It’s like heapq (which is blazingly fast) but it’s object-oriented and has more features.

Why?

Less code.

Easy Removal.

No need to re-invent the wheel.

How?

Before:

import heapq

heap = [1234, 12]
heapq.heapify(heap)
heapq.heappush(heap, 55)
print(heapq.heappop(heap))

After:

from xheap import Heap

heap = Heap([1234, 12])
heap.push(55)
print(heap.pop())

About that removal of items …

Imagine a priority queue of tasks. Say, you need to remove an arbitrary item from it. Just call remove.

heap = Heap([4, 3, 7, 6, 1, 2, 9, 8, 0, 5])
heap.remove(6)

If you know the item’s index, you can use pop.

heap = Heap([4, 3, 7, 6, 1, 2, 9, 8, 0, 5])
heap.pop(3)

Max-Heap or Min-Heap?

You define the order of items. Just imagine two heaps of the very same set of items but you need different sorting for each heap. So, you define what min and max means, via cmp.

items = [date(2015, 1, 1), date(2015, 1, 2),  date(2015, 1, 3)]
order1 = Heap(items, cmp=lambda x, y: x.day <= y.day)
order2 = Heap(items, cmp=lambda x, y: x.weekday() >= y.weekday())

Checking Heap Invariant

If you tinker with a heap you can check whether the heap invariant still holds:

heap = Heap([4, 3, 7, 6, 1, 2, 9, 8, 0, 5])
heap[3] = 0            # I know what I am doing here
heap.check_invariant() # but better check... ooops

Conclusion

Good

  • object-oriented

  • can remove items from within the heap

  • can remove items with unknown index

  • sorting defined per heap (falls back to Pythonic <=)

  • works with Python2 and Python3

Bad

  • no drawbacks discovered so far ;)

  • needs fix:

    • decrease-key and increase-key seem to be another important missing use-case of heapq; so, I will dig into that as well

    • merge heaps

  • ideas are welcome :-)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xheap-0.1.tar.gz (3.6 kB view hashes)

Uploaded Source

Built Distribution

xheap-0.1-py2.py3-none-any.whl (3.0 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page