本文整理汇总了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
示例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
示例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)
示例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
示例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}}
示例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
示例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
示例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()
示例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.
示例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
示例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)),
}
示例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
示例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.
示例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
示例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)