logoalt Hacker News

krautsaueryesterday at 5:09 PM2 repliesview on HN

One reason you don't see a data structure with O(log(n)) operations in this list is that priority queues/heaps are not a built-in type. Weirdly, there isn't a type for them at all, just a bunch of functions (good luck if you use them wrong). https://docs.python.org/3/library/heapq.html


Replies

Retr0idyesterday at 8:09 PM

It's not exposed for general use (yet?) but cpython does internally contain an implementation of the HAMT data structure: https://github.com/python/cpython/blob/main/Python/hamt.c

Set/Delete/Lookup are all O(log(n))

See also: https://github.com/MagicStack/immutables (for something you can actually use)

p.s. I think the reason heapq isn't a type is that it's ancient code that's hung around from the early days of python.

zahlmanyesterday at 7:12 PM

There isn't a type for them for the same kind of reasons that `join` is a method on the joining string. That is, it lets you reuse that code for multiple sequence types, including ones that don't exist yet. This is just something that happens with ad-hoc polymorphism, but it's also good to keep class interfaces small and implement other functionality in terms of them. Herb Sutter would approve.

Making the functions into methods wouldn't make them easier to use, it would just make the abstraction feel more familiar to those from a Java tradition rather than a C++ one.