[Tutor] how to keep track of sorted lists

Albert-Jan Roskam fomcl at yahoo.com
Sat Nov 3 14:04:54 CET 2012


Hello,

I want to make a get() method that uses a binary search. This requires the data to be sorted which is an expensive operation, so I would like to do this no more often than needed.
Which of the to classes below is the best way to keep track of the sorted lists? TestOne stores them in separate attributes, while TestTwo uses one sorted_ attribute that is a dictionary that contains all the sorted data, with keys as, well, keys. I am inclined to think that TestTwo is less messy. Btw, I am aware that, either way, it may not be a good idea to store all these potentially huge sorted lists.

Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55) 
[GCC 4.4.5] on linux2
>>> import bisect
>>> class TestOne(object):
    def __init__(self, param="x"):
        self.param = param
        self.data = range(10, 1, -1)
    def get(self, key):
        sorted_ = "sorted_" + self.param
        if not hasattr(self, sorted_):
            setattr(self, sorted_, sorted(self.data))
        return bisect.bisect_right(getattr(self, sorted_), x=key)
>>> t = TestOne("x")
>>> t.get(1)
0
>>> class TestTwo(object):
    def __init__(self, param="x"):
        self.param = param
        self.data = range(10, 1, -1)
    def get(self, key):
        k = "sorted_" + self.param
        if not hasattr(self, "sorted_"):
            setattr(self, "sorted_", {k: sorted(self.data)})
        return bisect.bisect_right(getattr(self, "sorted_")[k], x=key)
>>> t = TestTwo("x")
>>> t.get(1)
0
 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list