why not bisect options?

Robert Bossy Robert.Bossy at jouy.inra.fr
Fri Feb 29 15:31:54 CET 2008


Hi all,

I thought it would be useful if insort and consorts* could accept the 
same options than list.sort, especially key and cmp.

The only catch I can think of is that nothing prevents a crazy developer 
to insort elements using different options to the same list. I foresee 
two courses of actions:
1) let the developer be responsible for the homogeneity of successive 
insort calls on the same list (remember that the developer is already 
responsible for giving a sorted list), or
2) make bisect a class which keeps the key and cmp options internally 
and always use them for comparison, something like:


class Bisect:
    def __init__(self, lst = [], key = None, cmp = None):
        self.key = key
        self.cmp = cmp
        self.lst = lst
        self.lst.sort(key = key, cmp = cmp)

    def compare_elements(self, a, b):
        if self.cmp is not None:
            return self.cmp(a, b)
        if self.key is not None:
            return cmp(self.key(a), self.key(b))
        return cmp(a,b)

    def insort_right(self, elt, lo = 0, hi = None):
        """Inspired from bisect in the python standard library"""
        if hi is None:
            hi = len(self.lst)
        while lo < hi:
            mid = (lo + hi) / 2
            if self.compare_elements(elt, self.lst[mid]) < 0:
                hi = mid
            else:
                lo = mid + 1
        self.lst.insert(lo, elt)
    ...


Any thoughts about this?

RB

* at this point you should smile...



More information about the Python-list mailing list