I recently came across some Java code that simply put some strings into a Java TreeSet, implemented a distance based comparator for it, and then made its merry way into the sunset to compute a given score to solve the given problem.
My questions,
-
Is there an equivalent data structure available for Python?
- The Java treeset looks basically to be an ordered dictionary that can use a comparator of some sort to achieve this ordering.
-
I see there’s a PEP for Py3K for an OrderedDict, but I’m using 2.6.x. There are a bunch of ordered dict implementations out there – anyone in particular that can be recommended?
PS, Just to add – I could probably import DictMixin or UserDict and implement my own sorted/ordered dictionary, AND make it happen through a comparator function – but that seems to be overkill.
Thanks.
Update. Thanks for the answers. To elaborate a bit, lets say I’ve got a compare function thats defined like, (given a particular value ln),
def mycmp(x1, y1, ln):
a = abs(x1-ln)
b = abs(y1-ln)
if a<b:
return -1
elif a>b:
return 1
else:
return 0
I’m a bit unsure about how I’d integrate this into the ordering given in the ordered dict link given here...
Something like,
OrderedDict(sorted(d.items(), cmp=mycmp(len)))
Ideas would be welcome.
The Python 2.7 docs for
collections.OrderedDicthas a link to a OrderedDict recipe that runs on Python 2.4 or better.Edit: In regard to sorting: Use
key=rather thancmp=. It tends to lead to faster code and moreover, thecmp=keyword has been eliminated in Python3.The code you posted for
mycmpdoesn’t make it clear what you want passed asx1. Below, I assume x1 is supposed to be the value in each key-value pair. If so, you could do something like this:key=...is passed a function,lambda item: abs(item[1]-length).For each
itemind.items(), the lambda function returns the numberabs(item[1]-length). This number acts as proxy for the item as far as sorting is concerned. See this essay for more information on sorting idioms in Python.PS.
lenis a Python builtin function. So as to not clobber thatlen, I’ve changed the variable name tolength.