當前位置: 首頁>>代碼示例>>Python>>正文


Python bisect.insort方法代碼示例

本文整理匯總了Python中bisect.insort方法的典型用法代碼示例。如果您正苦於以下問題:Python bisect.insort方法的具體用法?Python bisect.insort怎麽用?Python bisect.insort使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bisect的用法示例。


在下文中一共展示了bisect.insort方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _release

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def _release(self, offset, width):
        # Coalesce
        while True:
            f,b,ndx = self._buddy(offset, width)

            if ndx is None:
                break
            
            offset &= b
            width += 1
            del f[ndx]
            
        # Add to the list
        bisect.insort(f, offset)

        # Mark as dirty
        self._dirty = True 
開發者ID:al45tair,項目名稱:ds_store,代碼行數:19,代碼來源:buddy.py

示例2: Add

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:20,代碼來源:local_scores.py

示例3: Add

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1
    RankerCacher.CachePut(self) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:21,代碼來源:result_ranker.py

示例4: interpret_interactions

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def interpret_interactions(w_input, w_later, get_main_effects=False):
    interaction_strengths = {}
    for i in range(w_later.shape[1]):
        sorted_hweights = sorted(
            enumerate(w_input[i]), key=lambda x: x[1], reverse=True
        )
        interaction_candidate = []
        candidate_weights = []
        for j in range(w_input.shape[1]):
            bisect.insort(interaction_candidate, sorted_hweights[j][0])
            candidate_weights.append(sorted_hweights[j][1])

            if not get_main_effects and len(interaction_candidate) == 1:
                continue
            interaction_tup = tuple(interaction_candidate)
            if interaction_tup not in interaction_strengths:
                interaction_strengths[interaction_tup] = 0
            interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i]))
            interaction_strengths[interaction_tup] += interaction_strength

    interaction_ranking = sorted(
        interaction_strengths.items(), key=operator.itemgetter(1), reverse=True
    )

    return interaction_ranking 
開發者ID:mtsang,項目名稱:neural-interaction-detection,代碼行數:27,代碼來源:neural_interaction_detection.py

示例5: add_order_to_book

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def add_order_to_book(self, order):
        '''
        Use insort to maintain on ordered list of prices which serve as pointers
        to the orders.
        '''
        book_order = {'order_id': order['order_id'], 'timestamp': order['timestamp'], 'type': order['type'], 
                      'quantity': order['quantity'], 'side': order['side'], 'price': order['price']}
        if order['side'] == 'buy':
            book_prices = self._bid_book_prices
            book = self._bid_book
        else:
            book_prices = self._ask_book_prices
            book = self._ask_book 
        if order['price'] in book_prices:
            book[order['price']]['num_orders'] += 1
            book[order['price']]['size'] += order['quantity']
            book[order['price']]['order_ids'].append(order['order_id'])
            book[order['price']]['orders'][order['order_id']] = book_order
        else:
            bisect.insort(book_prices, order['price'])
            book[order['price']] = {'num_orders': 1, 'size': order['quantity'], 'order_ids': [order['order_id']],
                                    'orders': {order['order_id']: book_order}} 
開發者ID:JackBenny39,項目名稱:pyziabm,代碼行數:24,代碼來源:orderbook3.py

示例6: add_item

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def add_item(self, item):
        item.date = self._convertunix(item.date)
        if item.date == None: return
        dt = datetime.fromtimestamp(item.date)
        try:
            item_day = dt.strftime('%d')
            item_month = dt.strftime('%b')
            item_year = dt.strftime('%Y')
        except:
            return
        
        key = self._DATES_KEYFORM.format(day=item_day,month=item_month,
                                         year=item_year)
        if key in self.timeline_dates:
            self.timeline_dates[key].add_item(item)
        else:
            day_date = datetime.fromtimestamp(item.date).date()
            day_tsmp = time.mktime(day_date.timetuple())
            timeline_date = TimelineDate( day_tsmp, item_day, item_month, 
                                          item_year, [item] )
            bisect.insort(self.items, timeline_date)
            self.timeline_dates[key] = timeline_date
        return 
開發者ID:georgenicolaou,項目名稱:nfi,代碼行數:25,代碼來源:Timeline.py

示例7: pickUnique

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def pickUnique(N, m, e):
    """Pick m random values from the range 0...(N-1), excluding those in list e
    The returned values should be in a random order (not sorted)
    """
    assert m <= N - len(e)
    
    inds = sorted(e) # Sorted list of indices. Used to avoid clashes
    others = [] # The list of three agents
    for i in range(m):
        newind = random.randint(0, N-1-i-len(e))
        for ind in inds:
            if newind == ind:
                newind += 1
        bisect.insort(inds, newind)
        others.append(newind)
    return others 
開發者ID:bendudson,項目名稱:freegs,代碼行數:18,代碼來源:optimiser.py

示例8: add_backer

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def add_backer(self, start, data):
        """
        Adds a backer to the memory.

        :param start:   The address where the backer should be loaded.
        :param data:    The backer itself. Can be either a bytestring or another :class:`Clemory`.
        """
        if not data:
            raise ValueError("Backer is empty!")

        if not isinstance(data, (bytes, bytearray, list, Clemory)):
            raise TypeError("Data must be a bytes, list, or Clemory object.")
        if start in self:
            raise ValueError("Address %#x is already backed!" % start)
        if isinstance(data, Clemory) and data._root:
            raise ValueError("Cannot add a root clemory as a backer!")
        if type(data) is bytes:
            data = bytearray(data)
        bisect.insort(self._backers, (start, data))
        self._update_min_max() 
開發者ID:angr,項目名稱:cle,代碼行數:22,代碼來源:memory.py

示例9: teardown

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def teardown(self):
        '''
        :return: 1 if any test failed, 0 otherwise
        '''
        self.log_info('\nTest result summary:')
        passes = []
        fails = []
        while not self.test_results.empty():
            test = self.test_results.get()
            if test.status in (TestStatus.PASS, None):
                bisect.insort(passes, test)
            else:
                bisect.insort(fails, test)
        for test in itertools.chain(passes, fails):
            self.log_info(test)
        if fails:
            self.log_error('A test failed')
            return 1
        return 0

# IO format. 
開發者ID:cirosantilli,項目名稱:linux-kernel-module-cheat,代碼行數:23,代碼來源:common.py

示例10: update

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def update(self, entry_id, label):
        bisect.insort(a=self.Lindex, x=entry_id)
        self.Uindex.remove(entry_id)
        self.y[entry_id] = label 
開發者ID:ntucllab,項目名稱:libact,代碼行數:6,代碼來源:quire.py

示例11: qkchash

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def qkchash(header: bytes, nonce: bytes, cache: List) -> Dict[str, bytes]:
    s = sha3_512(header + nonce[::-1])
    lcache = cache[:]
    lcache_set = set(cache)

    mix = []
    for i in range(2):
        mix.extend(s)

    for i in range(ACCESS_ROUND):
        new_data = []

        p = fnv64(i ^ s[0], mix[i % len(mix)])
        for j in range(len(mix)):
            # Find the pth element and remove it
            remove_idx = p % len(lcache)
            new_data.append(lcache[remove_idx])
            lcache_set.remove(lcache[remove_idx])
            del lcache[remove_idx]

            # Generate random data and insert it
            p = fnv64(p, new_data[j])
            if p not in lcache_set:
                bisect.insort(lcache, p)
                lcache_set.add(p)

            # Find the next element
            p = fnv64(p, new_data[j])

        for j in range(len(mix)):
            mix[j] = fnv64(mix[j], new_data[j])

    cmix = []
    for i in range(0, len(mix), 4):
        cmix.append(fnv64(fnv64(fnv64(mix[i], mix[i + 1]), mix[i + 2]), mix[i + 3]))
    return {
        "mix digest": serialize_hash(cmix),
        "result": serialize_hash(sha3_256(s + cmix)),
    } 
開發者ID:QuarkChain,項目名稱:pyquarkchain,代碼行數:41,代碼來源:qkchash.py

示例12: add_transaction

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def add_transaction(self, tx: TypedTransaction):
        evm_tx = tx.tx.to_evm_tx()
        if len(self.txs) >= self.limit:
            if evm_tx.gasprice < self.txs[-1].tx.tx.to_evm_tx().gasprice:
                return  # no-op
            pop_tx = self.txs.pop(-1).tx  # type: TypedTransaction
            self.tx_dict.pop(pop_tx.get_hash(), None)
        prio = -evm_tx.gasprice
        ordered_tx = OrderableTx(prio, self.counter, tx)
        # amortized O(n) cost, ~9x slower than heapq push, may need optimization if becoming a bottleneck
        bisect.insort(self.txs, ordered_tx)
        self.tx_dict[tx.get_hash()] = ordered_tx
        self.counter += 1 
開發者ID:QuarkChain,項目名稱:pyquarkchain,代碼行數:15,代碼來源:transaction_queue.py

示例13: nsmallest

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def nsmallest(n, iterable):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable)[:n]
    """
    if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
        # For smaller values of n, the bisect method is faster than a minheap.
        # It is also memory efficient, consuming only n elements of space.
        it = iter(iterable)
        result = sorted(islice(it, 0, n))
        if not result:
            return result
        insort = bisect.insort
        pop = result.pop
        los = result[-1]    # los --> Largest of the nsmallest
        for elem in it:
            if cmp_lt(elem, los):
                insort(result, elem)
                pop()
                los = result[-1]
        return result
    # An alternative approach manifests the whole iterable in memory but
    # saves comparisons by heapifying all at once.  Also, saves time
    # over bisect.insort() which has O(n) data movement time for every
    # insertion.  Finding the n smallest of an m length iterable requires
    #    O(m) + O(n log m) comparisons.
    h = list(iterable)
    heapify(h)
    return map(heappop, repeat(h, min(n, len(h))))

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore the
# heap invariant. 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:35,代碼來源:heapq.py

示例14: _free

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:31,代碼來源:heap.py

示例15: __setitem__

# 需要導入模塊: import bisect [as 別名]
# 或者: from bisect import insort [as 別名]
def __setitem__(self, key, value):
        assert key not in self, "MetersDict doesn't support reassignment"
        priority, value = value
        bisect.insort(self.priorities, (priority, len(self.priorities), key))
        super().__setitem__(key, value)
        for _, _, key in self.priorities:  # reorder dict to match priorities
            self.move_to_end(key) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:9,代碼來源:meters.py


注:本文中的bisect.insort方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。