Python bisect.insort_left() Examples

The following are 23 code examples of bisect.insort_left(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bisect , or try the search function .
Example #1
Source File: binary.py    From plasma with GNU General Public License v3.0 6 votes vote down vote up
def add_section(self, start_address, name, virt_size, real_size,
                    is_exec, is_data, is_bss, data):
        if is_exec or is_data:
            bisect.insort_left(self._sorted_sections, start_address)
        self._abs_sections[start_address] = SectionAbs(
                name,
                start_address,
                virt_size,
                real_size,
                is_exec,
                is_data,
                is_bss,
                data)


    # for elf 
Example #2
Source File: binary_search_examples.py    From Algorithm_Templates with MIT License 5 votes vote down vote up
def put(self, id: int, timestamp: str) -> None:
        bisect.insort_left(self.logs, (timestamp, id))

    # O(log(n)) to binary search 
Example #3
Source File: brill_trainer.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _update_tag_positions(self, rule):
        """
        Update _tag_positions to reflect the changes to tags that are
        made by *rule*.
        """
        # Update the tag index.
        for pos in self._positions_by_rule[rule]:
            # Delete the old tag.
            old_tag_positions = self._tag_positions[rule.original_tag]
            old_index = bisect.bisect_left(old_tag_positions, pos)
            del old_tag_positions[old_index]
            # Insert the new tag.
            new_tag_positions = self._tag_positions[rule.replacement_tag]
            bisect.insort_left(new_tag_positions, pos) 
Example #4
Source File: brill_trainer.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def _update_tag_positions(self, rule):
        """
        Update _tag_positions to reflect the changes to tags that are
        made by *rule*.
        """
        # Update the tag index.
        for pos in self._positions_by_rule[rule]:
            # Delete the old tag.
            old_tag_positions = self._tag_positions[rule.original_tag]
            old_index = bisect.bisect_left(old_tag_positions, pos)
            del old_tag_positions[old_index]
            # Insert the new tag.
            new_tag_positions = self._tag_positions[rule.replacement_tag]
            bisect.insort_left(new_tag_positions, pos) 
Example #5
Source File: timeseries.py    From test_driven_python with MIT License 5 votes vote down vote up
def update(self, timestamp, value):
        bisect.insort_left(self.series, Update(timestamp, value)) 
Example #6
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_arg_parsing(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(TypeError, f, 10)

#============================================================================== 
Example #7
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_get_only(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(AttributeError, f, GetOnly(), 10) 
Example #8
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_len_only(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(AttributeError, f, LenOnly(), 10) 
Example #9
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_non_sequence(self):
        for f in (bisect_left, bisect_right, insort_left, insort_right):
            self.assertRaises(TypeError, f, 10, 10) 
Example #10
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
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) 
Example #11
Source File: test_bisect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
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])

#============================================================================== 
Example #12
Source File: taskqueue_stub.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _PostponeTaskInsertOnly(self, task, new_eta_usec):
    assert self._lock.locked()
    task.set_eta_usec(new_eta_usec)
    name = task.task_name()
    bisect.insort_left(self._sorted_by_eta, (new_eta_usec, name, task))
    if task.has_tag():
      tag = task.tag()
      bisect.insort_left(self._sorted_by_tag, (tag, new_eta_usec, name, task)) 
Example #13
Source File: taskqueue_stub.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _InsertTask(self, task):
    """Insert a task into the store, keeps lists sorted.

    Args:
      task: the new task.
    """
    assert self._lock.locked()
    eta = task.eta_usec()
    name = task.task_name()
    bisect.insort_left(self._sorted_by_eta, (eta, name, task))
    if task.has_tag():
      bisect.insort_left(self._sorted_by_tag, (task.tag(), eta, name, task))
    bisect.insort_left(self._sorted_by_name, (name, task))
    self.task_name_archive.add(name) 
Example #14
Source File: taskqueue_stub.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _InsertTask(self, task):
    """Insert a task into the dummy store, keeps lists sorted.

    Args:
      task: the new task.
    """
    eta = task.eta_usec()
    name = task.task_name()
    bisect.insort_left(self._sorted_by_eta, (eta, name, task))
    bisect.insort_left(self._sorted_by_name, (name, task)) 
Example #15
Source File: hierarchy.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _order_cluster_tree(Z):
    """
    Returns clustering nodes in bottom-up order by distance.

    Parameters
    ----------
    Z : scipy.cluster.linkage array
        The linkage matrix.

    Returns
    -------
    nodes : list
        A list of ClusterNode objects.
    """
    q = deque()
    tree = to_tree(Z)
    q.append(tree)
    nodes = []

    while q:
        node = q.popleft()
        if not node.is_leaf():
            bisect.insort_left(nodes, node)
            q.append(node.get_right())
            q.append(node.get_left())
    return nodes 
Example #16
Source File: state.py    From hase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_major(self, state: State) -> None:
        # NOTE: major means the interval stubs
        self.add(state)
        bisect.insort_left(self.major_index, state.index) 
Example #17
Source File: state.py    From hase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add(self, state: State) -> None:
        self.index_to_state[state.index] = state
        bisect.insort_left(self.ordered_index, state.index) 
Example #18
Source File: testing.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def _insort_call(self, call):
        # We want to insert the call in the appropriate time slot. A simple
        # bisect.insort_left() is not sufficient as the comparison of two
        # methods is not defined in Python 3.
        times = [c[0] for c in self._calls]
        index = bisect.bisect_left(times, call[0])
        self._calls.insert(index, call) 
Example #19
Source File: branch_and_bound.py    From PLNN-verification with GNU General Public License v3.0 5 votes vote down vote up
def add_domain(candidate, domains):
    '''
    Use binary search to add the new domain `candidate`
    to the candidate list `domains` so that `domains` remains a sorted list.
    '''
    bisect.insort_left(domains, candidate) 
Example #20
Source File: msTools.py    From diploSHIC with MIT License 5 votes vote down vote up
def fillInSnpSlotsWithOverflowers(newPositions, totalPhysLen, overflowers):
    posH = {}
    for pos in newPositions:
        posH[pos] = 1
    for i in range(len(overflowers)):
        del newPositions[-1]
    for pos in reversed(range(1, totalPhysLen+1)):
        if pos not in posH:
            bisect.insort_left(newPositions, pos)
            overflowers.pop()
            if len(overflowers) == 0:
                break 
Example #21
Source File: hierarchy.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _order_cluster_tree(Z):
    """
    Return clustering nodes in bottom-up order by distance.

    Parameters
    ----------
    Z : scipy.cluster.linkage array
        The linkage matrix.

    Returns
    -------
    nodes : list
        A list of ClusterNode objects.
    """
    q = deque()
    tree = to_tree(Z)
    q.append(tree)
    nodes = []

    while q:
        node = q.popleft()
        if not node.is_leaf():
            bisect.insort_left(nodes, node)
            q.append(node.get_right())
            q.append(node.get_left())
    return nodes 
Example #22
Source File: hierarchy.py    From lambda-packs with MIT License 5 votes vote down vote up
def _order_cluster_tree(Z):
    """
    Return clustering nodes in bottom-up order by distance.

    Parameters
    ----------
    Z : scipy.cluster.linkage array
        The linkage matrix.

    Returns
    -------
    nodes : list
        A list of ClusterNode objects.
    """
    q = deque()
    tree = to_tree(Z)
    q.append(tree)
    nodes = []

    while q:
        node = q.popleft()
        if not node.is_leaf():
            bisect.insort_left(nodes, node)
            q.append(node.get_right())
            q.append(node.get_left())
    return nodes 
Example #23
Source File: subscenter.py    From bazarr with GNU General Public License v3.0 4 votes vote down vote up
def query(self, title, season=None, episode=None):
        # search for the url title
        url_titles = self._search_url_titles(title)

        # episode
        if season and episode:
            if 'series' not in url_titles:
                logger.error('No URL title found for series %r', title)
                return []
            url_title = url_titles['series'][0]
            logger.debug('Using series title %r', url_title)
            url = self.server_url + 'cst/data/series/sb/{}/{}/{}/'.format(url_title, season, episode)
            page_link = self.server_url + 'subtitle/series/{}/{}/{}/'.format(url_title, season, episode)
        else:
            if 'movie' not in url_titles:
                logger.error('No URL title found for movie %r', title)
                return []
            url_title = url_titles['movie'][0]
            logger.debug('Using movie title %r', url_title)
            url = self.server_url + 'cst/data/movie/sb/{}/'.format(url_title)
            page_link = self.server_url + 'subtitle/movie/{}/'.format(url_title)

        # get the list of subtitles
        logger.debug('Getting the list of subtitles')
        r = self.session.get(url)
        r.raise_for_status()
        results = json.loads(r.text)

        # loop over results
        subtitles = {}
        for language_code, language_data in results.items():
            for quality_data in language_data.values():
                for quality, subtitles_data in quality_data.items():
                    for subtitle_item in subtitles_data.values():
                        # read the item
                        language = Language.fromalpha2(language_code)
                        hearing_impaired = bool(subtitle_item['hearing_impaired'])
                        subtitle_id = subtitle_item['id']
                        subtitle_key = subtitle_item['key']
                        subtitle_version = subtitle_item['h_version']
                        downloaded = subtitle_item['downloaded']
                        release = subtitle_item['subtitle_version']

                        # add the release and increment downloaded count if we already have the subtitle
                        if subtitle_id in subtitles:
                            logger.debug('Found additional release %r for subtitle %d', release, subtitle_id)
                            bisect.insort_left(subtitles[subtitle_id].releases, release)  # deterministic order
                            subtitles[subtitle_id].downloaded += downloaded
                            continue

                        # otherwise create it
                        subtitle = self.subtitle_class(language, hearing_impaired, page_link, title, season, episode,
                                                      title, subtitle_id, subtitle_key, subtitle_version, downloaded,
                                                      [release])
                        logger.debug('Found subtitle %r', subtitle)
                        subtitles[subtitle_id] = subtitle

        return list(subtitles.values())