[Tutor] how to keep track of sorted lists

Albert-Jan Roskam fomcl at yahoo.com
Sat Nov 3 15:40:47 CET 2012


> On 11/03/2012 09:04 AM, Albert-Jan Roskam wrote:

>>  Hello,
> 
> (I haven't run the code, as it was not presented in a form that I could
> do a single copy/paste.  So I may have missed some subtlety in the code.)

Hi, sorry about that. Here's a copy/pastable version. I also added a 'data' parameter as my original code was too synthetic in this respect.
The more realistically, the data come from some getter method.

import bisect
class TestOne(object):
    def __init__(self, data, param="x"):
        self.param = param
        self.data = data  # <------ NOTE: this would in reality be a getter method of some sort
    def get(self, key, default=None):
        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(range(10, 1, -1), "x")
t.get(1)

class TestTwo(object):
    def __init__(self, data, param="x"):
        self.param = param
        self.data = range(10, 1, -1)
    def get(self, key, default=None):
        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(range(10, 1, -1), "x")
t.get(1)

<snip>
    return bisect.bisect_right(getattr(self, sorted_), x=key)
> 
> Why have multiple copies of the sorted data, when there's only one list?
> 
<snip>

> Good job simplifying the problem.  But it's so simple i can't see what
> the real goal is without some textual description.  Is a single instance
> of this class intended to hold a single, unchanging list?  If not, are
> you intending to delete the sorted_ attribute each time it changes?
> 

The get() method is supposed to mimic the dict.get method. I want to do stuff like:
c = TestOne(data=blah, param="ssn") # ---> c.sorted_snn
c.get(432123, "social security number not found")
d = TestOne(data=blah, param="gender") # ---> d.sorted_gender
d.get("female", "sorry, only blokes here")



More information about the Tutor mailing list