我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bisect.bisect()。
def _find(self, path): path = path[self.prefix_len:] if path in self._files: result = True else: if path and path[-1] != os.sep: path = path + os.sep i = bisect.bisect(self.index, path) try: result = self.index[i].startswith(path) except IndexError: result = False if not result: logger.debug('_find failed: %r %r', path, self.loader.prefix) else: logger.debug('_find worked: %r %r', path, self.loader.prefix) return result
def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.random if cum_weights is None: if weights is None: _int = int total = len(population) return [population[_int(random() * total)] for i in range(k)] cum_weights = list(_itertools.accumulate(weights)) elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != len(population): raise ValueError('The number of weights does not match the population') bisect = _bisect.bisect total = cum_weights[-1] return [population[bisect(cum_weights, random() * total)] for i in range(k)] ## -------------------- real-valued distributions ------------------- ## -------------------- uniform distribution -------------------
def is_read_exonic(aligned_segments, exon_breaks, first_exon, last_exon, min_overlap_frac=0.5): for read_start, read_end, _ in aligned_segments: ex_idx = bisect.bisect(exon_breaks, read_start, lo=2*first_exon, hi=2*(last_exon+1)) - 1 if ex_idx > 2*last_exon: # read is out of bounds return False elif ex_idx % 2 == 1: # read starts in an intron exon_start = exon_breaks[ex_idx+1] exon_end = exon_breaks[ex_idx+2] else: # read starts in an exon exon_start = exon_breaks[ex_idx] exon_end = exon_breaks[ex_idx+1] segment_exonic = overlaps(read_start, read_end, exon_start, exon_end, min_overlap_frac) if not segment_exonic: return False return True
def add_region(self, reg): """ Adds single region to set while removing overlap """ # in case not given as named tuple region = Region(reg[0], reg[1]) # find where this region should go start_index = bisect.bisect_left(self.starts, region.start) end_index = bisect.bisect_left(self.ends, region.end) # merge if required if start_index > 0 and self.ends[start_index-1] > region.start: region = Region(self.starts[start_index-1], region.end) start_index -= 1 if end_index < len(self.starts) and self.starts[end_index] < region.end: region = Region(region.start, self.ends[end_index]) end_index += 1 # if no merge, insert this region in the lists if start_index == end_index: self.starts = self.starts[:start_index] + [region.start] + self.starts[start_index:] self.ends = self.ends[:start_index] + [region.end] + self.ends[start_index:] else: self.starts = self.starts[:start_index] + [region.start] + self.starts[end_index:] self.ends = self.ends[:start_index] + [region.end] + self.ends[end_index:]
def get_closest_region(self, pt): """ Returns the start and end of the closest region, and whether the region contains the point """ containining_region = self.get_region_containing_point(pt) if not(containining_region is None): (start, end) = containining_region return (start, end, True) right_index = bisect.bisect(self.starts, pt) left_index = right_index - 1 if right_index == 0: return (self.starts[right_index], self.ends[right_index], False) elif right_index == len(self.starts): return (self.starts[left_index], self.ends[left_index], False) else: left_dist = pt - self.ends[left_index] right_dist = self.starts[right_index] - pt if left_dist < right_dist: return (self.starts[left_index], self.ends[left_index], False) else: return (self.starts[right_index], self.ends[right_index], False)
def update(self,record,**kw): """Update the record with new keys and values and update indices""" # update indices _id = record["__id__"] for indx in self.indices.keys(): if indx in kw.keys(): if record[indx] == kw[indx]: continue # remove id for the old value old_pos = bisect.bisect(self.indices[indx][record[indx]],_id)-1 del self.indices[indx][record[indx]][old_pos] if not self.indices[indx][record[indx]]: del self.indices[indx][record[indx]] # insert new value bisect.insort(self.indices[indx].setdefault(kw[indx],[]),_id) # update record values record.update(kw) # increment version number record["__version__"] += 1
def is_in(self, w, mapping): r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like:: \bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted. """ p = bisect(mapping, (w,)) if p > 0: if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \ mapping[p-1][1][:len(w)] == w: return True if p < len(mapping): return mapping[p][0] == w[:len(mapping[p][0])] and \ mapping[p][1][:len(w)] == w return False
def get_index(self, value, key="name"): value = value.lower().replace(" ", "") if key == "name": index = bisect.bisect(self.db_names, value) - 1 if self.db_names[index] == value: return index else: return -1 try: index = self.db_abbrevs.index(value) except ValueError: index = -1 return index
def add_to_surname_list(self, person, batch_transaction): """ Add surname to surname list """ if batch_transaction: return name = None primary_name = person.get_primary_name() if primary_name: surname_list = primary_name.get_surname_list() if len(surname_list) > 0: name = surname_list[0].surname if name is None: return i = bisect.bisect(self.surname_list, name) if 0 < i <= len(self.surname_list): if self.surname_list[i-1] != name: self.surname_list.insert(i, name) else: self.surname_list.insert(i, name)
def _update_explicit_bucket_count(a_float, dist): """Adds `a_float` to `dist`, updating its explicit buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueError: if `dist` does not already have explict buckets defined ValueError: if there are not enough bucket count fields in `dist` """ buckets = dist.explicitBuckets if buckets is None: raise ValueError(_BAD_UNSET_BUCKETS % (u'explicit buckets')) bucket_counts = dist.bucketCounts bounds = buckets.bounds if len(bucket_counts) < len(bounds) + 1: raise ValueError(_BAD_LOW_BUCKET_COUNT) bucket_counts[bisect.bisect(bounds, a_float)] += 1
def close_outer(itr, b): """ For sorted iterable `itr` and numeric `b`, return the index of the value in itr that is closest to b. Also return the value itself and the distance between itr and b. """ i, length, first, last = bisect(itr, b), len(itr), itr[0], itr[-1] if i == length: return length - 1, last, b - last if i == 0: return 0, first, first - b vnext, vprev = itr[i], itr[i - 1] dnext, dprev = vnext - b, b - vprev if dnext < dprev: return i, vnext, dnext return i - 1, vprev, dprev