How to pass a C structure in Python?

Why is there no data structure in python stdlib which can be used as a sorted set?

  • I'm well versed with Java and C++ and both have structures implemented as balanced binary trees that support sorted iterable sets. Python only has lists or hash tables but no structure built over balanced binary trees. In particular I want following operations which I think are fairly common and I'm unable to find a standard structure in python that can help me: O(log N) insert O(log N) find O(log N) remove O(1) iteration per element (on average), iteration from the smallest element to the largest Best I can think of is making use of heapq structure (for iteration, using nlargest with powers of 2). What is the pythonic way of going about it?

  • Answer:

    At the risk of sarcasm: the Pythonic way is to stop worrying and love the slow algorithm. (Probably using a list and sorting it at each insert. On the bright side, Python's sort implementation should be O(n) when all but the last element is already sorted.) Alternatively, drop into Cython or C and write your own. Or use where somebody on the internet has already done that -- some examples come up in this search: http://pypi.python.org/pypi?%3Aaction=search&term=btree Maybe one of those is good.

Greg Price at Quora Visit the source

Was this solution helpful to you?

Other answers

I'd say the most Pythonic way to solve the problem is to turn to PyPI. There's no one-way to create a sorted set so that module isn't in the standard library. If you're smart enough to know you need one then you can pick from many third-party modules. You certainly don't need to "stop worrying and love the slow algorithm." Python can actually be as fast-as-C. For example, see the http://www.grantjenks.com/docs/sortedcontainers/ module. It's pure-Python and faster [http://www.grantjenks.com/docs/sortedcontainers/performance.html] than most competing C-implementations. There's more than half a dozen great options out there, pick one. Learn to love PyPI. It's really quite high-quality.

Grant Jenks

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.