[Tutor] how to keep track of sorted lists

Dave Angel d at davea.name
Sat Nov 3 15:47:22 CET 2012


On 11/03/2012 10:40 AM, Albert-Jan Roskam wrote:
>> 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")
> 
> 
> 

OK, so you have a separate instance of TestOne for each list, and the
list is not modified for that instance.  In that case, both your sample
code is overly complex;  you're not using param for anything useful, and
you could greatly simplify by using an ordinary attribute to hold the
sorted list.  If it's not present, generate it.  Or even easier,
initialize it to None, and do a simple "if self.sorted is not None"on it
to decide whether it's sorted yet or not.

-- 

DaveA


More information about the Tutor mailing list