[Tutor] how to keep track of sorted lists
Albert-Jan Roskam
fomcl at yahoo.com
Tue Nov 6 15:36:06 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?
>>>
I was already half way writing a reply when I (finally!) realized that you are absolutely right!
Maybe it's because I also considered using 'param' as a parameter of get() instead of __init__().
The code is needlessly complicated indeed, and mentioning bisect was distracting (and indeed,
the method was an index() method --I believe it was Steven who pointed that out). Thanks you all.
Cheers,
Albert-Jan (with occasionally fuzzy cortex ;-)
More information about the Tutor
mailing list