Coming from a C++ background I miss a nice sorted container that is only based on comparisons and does not need a hash.
Does anybody know a good implementation of a balanced tree? Or is there an alternative sorted container in the (standard) library that is just as easy to use?
This is my usecase that I try to solve now: A have a file describing a surface with triangles. Each triangle has three nodes, and many nodes will be the same. I need to reconstruct this surface and need to know which nodes are the same. Unfortunately, in the ASCII input, there are sometimes small differences between the printed floats even if they belong to the same node. So I can't use a simple text compare to see if they are equal.
In C++ my solution would be to make a std::map to store the nodes with a 'softcompare' that treats the nodes as equal if the distance between them is small. Then I can just add the nodes while parsing the file and use an index to build the surface.
But in Python I'm struggling to do it equally efficiently in a straightforward way.
Thanks, Luke
Thanks all for your contributions!
To goncalopp: Sort is not a good alternative, because it is O(n log(n)) worst case on each insert. Same goes for bisect. It is good on search, but not on insert. It maintains an unbalanced tree which is O(n) in worst case and then the following insert in list is O(n).
To Aaron: I fully agree with you that the goal is to write elegant code. For me, choosing the right container (data structure) is often the first step to do this. Your solution is O(n) which is even faster then a balanced tree, very nice and I like the trick with the round(). I did not think of that, now I realize it works in python because of infinite precision of int. So I'll go with your construction.
To MrE: Thanks for the link to bintree, it looks like the solution for my question (balanced tree). I found blist before, but that uses an internal dict and hashes for lookup, so that didn't work, but bintree looks a lot better.