我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bisect.bisect_right()。
def script(char): """ Return the four-letter script code assigned to the Unicode character 'char' as string. >>> script("a") 'Latn' >>> script(",") 'Zyyy' >>> script(unichr(0x10FFFF)) 'Zzzz' """ code = byteord(char) # 'bisect_right(a, x, lo=0, hi=len(a))' returns an insertion point which # comes after (to the right of) any existing entries of x in a, and it # partitions array a into two halves so that, for the left side # all(val <= x for val in a[lo:i]), and for the right side # all(val > x for val in a[i:hi]). # Our 'SCRIPT_RANGES' is a sorted list of ranges (only their starting # breakpoints); we want to use `bisect_right` to look up the range that # contains the given codepoint: i.e. whose start is less than or equal # to the codepoint. Thus, we subtract -1 from the index returned. i = bisect_right(Scripts.RANGES, code) return Scripts.VALUES[i-1]
def script_extension(char): """ Return the script extension property assigned to the Unicode character 'char' as a set of string. >>> script_extension("a") == {'Latn'} True >>> script_extension(unichr(0x060C)) == {'Arab', 'Syrc', 'Thaa'} True >>> script_extension(unichr(0x10FFFF)) == {'Zzzz'} True """ code = byteord(char) i = bisect_right(ScriptExtensions.RANGES, code) value = ScriptExtensions.VALUES[i-1] if value is None: # code points not explicitly listed for Script Extensions # have as their value the corresponding Script property value return {script(char)} return value
def get_replicas(self, keyspace, token): """ Get a set of :class:`.Host` instances representing all of the replica nodes for a given :class:`.Token`. """ tokens_to_hosts = self.tokens_to_hosts_by_ks.get(keyspace, None) if tokens_to_hosts is None: self.rebuild_keyspace(keyspace, build_if_absent=True) tokens_to_hosts = self.tokens_to_hosts_by_ks.get(keyspace, None) if tokens_to_hosts: # token range ownership is exclusive on the LHS (the start token), so # we use bisect_right, which, in the case of a tie/exact match, # picks an insertion point to the right of the existing match point = bisect_right(self.ring, token) if point == len(self.ring): return tokens_to_hosts[self.ring[0]] else: return tokens_to_hosts[self.ring[point]] return []
def __getitem__(self, key): bounds, values = self._bounds, self._values if hasattr(key, 'start') and hasattr(key, 'stop'): # we are indexing with an interval. we only return the value # if that interval is contained within one of our intervals. start, stop = key.start, key.stop lindex = bisect_right(bounds, start) if start is not None else 0 rindex = (bisect_left(bounds, stop) if stop is not None else len(bounds)) if lindex != rindex: raise KeyError(key) return values[lindex] else: # We are indexing with a single element. result = values[bisect_right(bounds, key)] if result is self.nothing: raise KeyError(key) return result
def submapping(self, start, stop): bounds, values, nothing = self._bounds, self._values, self.nothing lindex = bisect_right(bounds, start) if start is not None else 0 rindex = (bisect_left(bounds, stop) if stop is not None else len(bounds)) res = type(self)() res._bounds = blist(bounds[lindex:rindex]) res._values = blist(values[lindex:rindex + 1]) if start is not None: res[:start] = nothing if stop is not None: res[stop:] = nothing return res
def get_statement_startend2(lineno, node): import ast # flatten all statements and except handlers into one lineno-list # AST's line numbers start indexing at 1 l = [] for x in ast.walk(node): if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler): l.append(x.lineno - 1) for name in "finalbody", "orelse": val = getattr(x, name, None) if val: # treat the finally/orelse part as its own statement l.append(val[0].lineno - 1 - 1) l.sort() insert_index = bisect_right(l, lineno) start = l[insert_index - 1] if insert_index >= len(l): end = None else: end = l[insert_index] return start, end
def blockname(ch): """Return the Unicode block name for ch, or None if ch has no block. >>> blockname(u'a') 'Basic Latin' >>> blockname(unichr(0x0b80)) 'Tamil' >>> block(unichr(2048)) None """ assert isinstance(ch, text_type) and len(ch) == 1, repr(ch) cp = ord(ch) i = bisect_right(_starts, cp) - 1 end = _ends[i] if cp > end: return None return _names[i]
def blocknum(ch): """Returns the unicode block number for ch, or None if ch has no block. >>> blocknum(u'a') 0 >>> blocknum(unichr(0x0b80)) 22 >>> blocknum(unichr(2048)) None """ cp = ord(ch) i = bisect_right(_starts, cp) - 1 end = _ends[i] if cp > end: return None return i
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float('inf') if t is None: return [] if p < t.center: retval = intervals_containing(t.left, p) j = bisect_right(t.by_low, (p, (INF, INF))) for i in range(j): retval.append(t.by_low[i][1]) else: retval = intervals_containing(t.right, p) i = bisect_right(t.by_high, (p, (INF, INF))) for j in range(i, len(t.by_high)): retval.append(t.by_high[j][1]) return retval # snip}
def add(self, val): """Add the element *val* to the list.""" _maxes, _lists = self._maxes, self._lists if _maxes: pos = bisect_right(_maxes, val) if pos == len(_maxes): pos -= 1 _maxes[pos] = val _lists[pos].append(val) else: insort(_lists[pos], val) self._expand(pos) else: _maxes.append(val) _lists.append([val]) self._len += 1
def bisect_right(self, val): """ Same as *bisect_left*, but if *val* is already present, the insertion point will be after (to the right of) any existing entries. """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, val) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], val) return self._loc(pos, idx)
def get_unstripped_pos(self, pos): """ After the feed has been processed. :param pos: The position of the "stripped" tag :return: Returns the position in the "unstripped" string. """ # Find out which segment we're in - always get the position to the # right of the one we want to be in. max_pos = self.pos_counts[-1][1] pos_counts_pos = bisect.bisect_right(self.pos_counts, (pos, max_pos)) pos_counts_pos -= 1 stripped_base, unstripped_base = self.pos_counts[pos_counts_pos] return unstripped_base + (pos - stripped_base)
def select(self, population, fitness): ''' Select a pair of parent using FPS algorithm. ''' # Normalize fitness values for all individuals. fit = population.all_fits(fitness) min_fit = min(fit) fit = [(i - min_fit) for i in fit] # Create roulette wheel. sum_fit = sum(fit) wheel = list(accumulate([i/sum_fit for i in fit])) # Select a father and a mother. father_idx = bisect_right(wheel, random()) father = population[father_idx] mother_idx = (father_idx + 1) % len(wheel) mother = population[mother_idx] return father, mother
def length(self, t0=None, t1=None): """ Computes the euclidian length of the curve in geometric space .. math:: \\int_{t_0}^{t_1}\\sqrt{x(t)^2 + y(t)^2 + z(t)^2} dt """ (x,w) = np.polynomial.legendre.leggauss(self.order(0)+1) knots = self.knots(0) # keep only integration boundaries within given start (t0) and stop (t1) interval if t0 is not None: i = bisect_left(knots, t0) knots = np.insert(knots, i, t0) knots = knots[i:] if t1 is not None: i = bisect_right(knots, t1) knots = knots[:i] knots = np.insert(knots, i, t1) t = np.array([ (x+1)/2*(t1-t0)+t0 for t0,t1 in zip(knots[:-1], knots[1:]) ]) w = np.array([ w/2*(t1-t0) for t0,t1 in zip(knots[:-1], knots[1:]) ]) t = np.ndarray.flatten(t) w = np.ndarray.flatten(w) dx = self.derivative(t) detJ = np.sqrt(np.sum(dx**2, axis=1)) return np.dot(detJ, w)
def iterate_from(self, start_tok): piecenum = bisect.bisect_right(self._offsets, start_tok)-1 while piecenum < len(self._pieces): offset = self._offsets[piecenum] piece = self._pieces[piecenum] # If we've got another piece open, close it first. if self._open_piece is not piece: if self._open_piece is not None: self._open_piece.close() self._open_piece = piece # Get everything we can from this piece. for tok in piece.iterate_from(max(0, start_tok-offset)): yield tok # Update the offset table. if piecenum+1 == len(self._offsets): self._offsets.append(self._offsets[-1] + len(piece)) # Move on to the next piece. piecenum += 1
def find_module(modlist, mod_addrs, addr): """Uses binary search to find what module a given address resides in. This is much faster than a series of linear checks if you have to do it many times. Note that modlist and mod_addrs must be sorted in order of the module base address.""" pos = bisect_right(mod_addrs, addr) - 1 if pos == -1: return None mod = modlist[mod_addrs[pos]] if (addr >= mod.DllBase.v() and addr < mod.DllBase.v() + mod.SizeOfImage.v()): return mod else: return None
def _find_utc_index(self, dt): lo, hi = 0, len(self._utc_transition_times) hint = self._local_hint.get('_utc') if hint: if dt == hint[0]: return hint[1] elif dt < hint[0]: hi = hint[1] + 1 else: lo = hint[1] idx = max(0, bisect_right(self._utc_transition_times, dt, lo, hi) - 1) self._local_hint['_utc'] = (dt, idx) return idx
def _find_nearest_size(self, size_candidate): index = bisect.bisect_right(self._possible_sizes, size_candidate) if index == 0: return self._possible_sizes[0] if index >= len(self._possible_sizes): return self._possible_sizes[-1] right_size = self._possible_sizes[index] left_size = self._possible_sizes[index - 1] if abs(size_candidate - right_size) < abs(size_candidate - left_size): return right_size else: return left_size
def add(self, val): """Add the element *val* to the list.""" _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, val) if pos == len(_maxes): pos -= 1 _lists[pos].append(val) _maxes[pos] = val else: insort(_lists[pos], val) self._expand(pos) else: _lists.append([val]) _maxes.append(val) self._len += 1
def __init__(self, table, key): self._table = table self._values = [] # ordered list of values self._rec_by_val = [] # matching record numbers self._records = {} # record numbers:values self.__doc__ = key.__doc__ or 'unknown' self._key = key self._previous_status = [] for record in table: value = key(record) if value is DoNotIndex: continue rec_num = recno(record) if not isinstance(value, tuple): value = (value, ) vindex = bisect_right(self._values, value) self._values.insert(vindex, value) self._rec_by_val.insert(vindex, rec_num) self._records[rec_num] = value table._indexen.add(self)
def __call__(self, record): rec_num = recno(record) key = self.key(record) if rec_num in self._records: if self._records[rec_num] == key: return old_key = self._records[rec_num] vindex = bisect_left(self._values, old_key) self._values.pop(vindex) self._rec_by_val.pop(vindex) del self._records[rec_num] assert rec_num not in self._records if key == (DoNotIndex, ): return vindex = bisect_right(self._values, key) self._values.insert(vindex, key) self._rec_by_val.insert(vindex, rec_num) self._records[rec_num] = key