[Tutor] how to keep track of sorted lists

Steven D'Aprano steve at pearwood.info
Sat Nov 3 16:30:06 CET 2012


On 04/11/12 01:40, Albert-Jan Roskam wrote:

> 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.

I don't understand what you mean by that.


> 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)

Default isn't used here. What's it for?

The name of this method, and its argument, are misleading. It isn't
a "get" method, like dicts have, it doesn't take a key and return an
item associated with that key. What you've actually written is a
complicated version of list.index, except that you can't distinguish
between item found and item not found.


> The get() method is supposed to mimic the dict.get method.

But it doesn't.


> 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")

Sounds like you want a dict.



-- 
Steven


More information about the Tutor mailing list