Python源码示例:bisect.insort_right()

示例1
def insort_right_rev(alist, new_element, low=0, high=None):
    """Similar to bisect.insort_right but for reverse sorted lists

    This code is similar to the Python code found in Lib/bisect.py.
    We simply change the comparison from 'less than' to 'greater than'.
    """

    if low < 0:
        raise ValueError('low must be non-negative')
    if high is None:
        high = len(alist)
    while low < high:
        middle = (low + high) // 2
        if new_element > alist[middle]:
            high = middle
        else:
            low = middle + 1
    alist.insert(low, new_element) 
示例2
def trigger(self):
        """
        触发一次定时器

        :return: 如果到时触发了一个定时器,则返回这个定时器的附属参数。否则返回None
        :rtype: str
        """

        with self._lock:
            if len(self._timer_queue) > 0 and self._timer_queue[0].current <= int(time.time()):
                top_timer = self._timer_queue.pop(0)
                param = top_timer.param
                top_timer.next()
                bisect.insort_right(self._timer_queue, top_timer)
                return param
            else:
                return None 
示例3
def addRange(self, ipmask):
        ip, mask = ipmask
        ipmask = (ip & mask, mask)

        # See if this range is already covered.
        if self.containsRange(ipmask):
            return

        # Delete any existing ranges that are covered by this new range.
        deletes = []
        for i, old_ipmask in enumerate(self.nets):
            if IsSubsetOf(old_ipmask, ipmask):
                deletes.append(i)
        for i in reversed(deletes):
            del self.nets[i]

        # Insert the new range
        bisect.insort_right(self.nets, ipmask) 
示例4
def add_partition(self, key, group):
        """Add sharding information for a group"""
        if self.shard_type == 'RANGE':
            key = int(key)
        elif self.shard_type == 'RANGE_DATETIME':
            try:
                if ':' in key:
                    key = datetime.strptime(key, "%Y-%m-%d %H:%M:%S")
                else:
                    key = datetime.strptime(key, "%Y-%m-%d").date()
            except:
                raise ValueError(
                    "RANGE_DATETIME key could not be parsed, was: {0}".format(
                        key
                    ))
        elif self.shard_type == 'RANGE_STRING':
            pass
        elif self.shard_type == "HASH":
            pass
        else:
            raise ValueError("Unsupported sharding type {0}".format(
                self.shard_type
            ))
        self.partitioning[key] = {
            'group': group,
        }
        self.reset_ttl()
        bisect.insort_right(self.keys, key)
        insort_right_rev(self.keys_reversed, key) 
示例5
def set_tab(self): # <ESC>H
        '''Sets a tab at the current position.'''
        r, c = self.cursor()
        bisect.insort_right(self._tabs, c) 
示例6
def register(
        self, what, when, func, on_tags, order, is_formatter=False, always=False
    ):
        """Register the given Hook for later execution"""
        if inspect.isgeneratorfunction(func):
            # the registered function is a generator hook
            hook_impl = GeneratorHookImpl(
                what, func, on_tags, order, is_formatter, always
            )

            if (
                hook_impl in self._hooks["before"][what]
                and hook_impl in self._hooks["after"][what]
            ):
                # NOTE: allow a Hook Implementation to be registered multiple times.
                #       This can happend when one hook module imports another in the same
                #       RADISH_BASEDIR.
                return

            # insert the HookImpl in the order given by ``order``.
            bisect.insort_right(self._hooks["before"][what], hook_impl)
            bisect.insort_right(self._hooks["after"][what], hook_impl)
        else:
            # we have regular hook
            hook_impl = HookImpl(what, when, func, on_tags, order, is_formatter, always)

            if hook_impl in self._hooks[when][what]:
                # NOTE: allow a Hook Implementation to be registered multiple times.
                #       This can happend when one hook module imports another in the same
                #       RADISH_BASEDIR.
                return

            # insert the HookImpl in the order given by ``order``.
            bisect.insort_right(self._hooks[when][what], hook_impl) 
示例7
def test_keyword_args(self):
        data = [10, 20, 30, 40, 50]
        self.assertEqual(bisect_left(a=data, x=25, lo=1, hi=3), 2)
        self.assertEqual(bisect_right(a=data, x=25, lo=1, hi=3), 2)
        self.assertEqual(bisect(a=data, x=25, lo=1, hi=3), 2)
        insort_left(a=data, x=25, lo=1, hi=3)
        insort_right(a=data, x=25, lo=1, hi=3)
        insort(a=data, x=25, lo=1, hi=3)
        self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50])

#============================================================================== 
示例8
def test_vsBuiltinSort(self, n=500):
        from random import choice
        for insorted in (list(), UserList()):
            for i in xrange(n):
                digit = choice("0123456789")
                if digit in "02468":
                    f = insort_left
                else:
                    f = insort_right
                f(insorted, digit)
        self.assertEqual(sorted(insorted), insorted) 
示例9
def test_backcompatibility(self):
        self.assertEqual(insort, insort_right)

#============================================================================== 
示例10
def test_non_sequence(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(TypeError, f, 10, 10) 
示例11
def test_len_only(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(AttributeError, f, LenOnly(), 10) 
示例12
def test_cmp_err(self):
        seq = [CmpErr(), CmpErr(), CmpErr()]
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(ZeroDivisionError, f, seq, 10) 
示例13
def test_arg_parsing(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(TypeError, f, 10)

#============================================================================== 
示例14
def add_domain(self, domain: Any, feature_name: str, subtype: str = "") -> None:
        """ Adds a domain to the current set.

            Arguments:
                domain: the domain to add, this should be a HMMResult-like object
            (see: antismash.common.hmmscan_refinement.HMMResult).
                feature_name: the name of the matching AntismashDomain feature
                              in the same record as this qualifier
                subtype: a specific subtype of the domain type, if any

            Returns:
                None
        """
        assert not isinstance(domain, str)
        if subtype:
            assert domain.hit_id == "PKS_KS", domain.hit_id
        if domain.hit_id == "PKS_AT":
            self.at_counter += 1
            suffix = "_AT%d" % self.at_counter
        elif domain.hit_id == "PKS_KR":
            self.kr_counter += 1
            suffix = "_KR%d" % self.kr_counter
        elif domain.hit_id == "CAL_domain":
            self.cal_counter += 1
            suffix = "_CAL%d" % self.cal_counter
        elif domain.hit_id in ["AMP-binding", "A-OX"]:
            self.a_counter += 1
            suffix = "_A%d" % self.a_counter
        elif domain.hit_id == "PKS_KS":
            self.ks_counter += 1
            suffix = "_KS%d" % self.ks_counter
        else:
            self.other_counter += 1
            suffix = "_OTHER%d" % self.other_counter

        new = NRPSPKSQualifier.Domain(domain.hit_id, suffix,
                                      domain.query_start, domain.query_end,
                                      domain.evalue, domain.bitscore, feature_name, subtype)
        bisect.insort_right(self._domains, new)
        # update the domain name list
        self._domain_names = [domain.name for domain in self._domains] 
示例15
def bookmarkAdd(self):
        """Adds a bookmark at the cursor's location. If multiple lines are
        selected, all existing bookmarks in those lines are overwritten with the
        new bookmark.

        Args:
          None.

        Returns:
          None.
        """
        newBookmark = self.dataToBookmark()
        self.bookmarkRemove()
        bisect.insort_right(self.bookmarks, newBookmark)