def find_source(sourcemap_index, lineno, colno): """ Given a SourceMapIndex and a transformed lineno/colno position, return the SourceMap object (which contains original file, line, column, and token name) """ # error says "line no 1, column no 56" assert lineno > 0, 'line numbers are 1-indexed' if isinstance(sourcemap_index, IndexedSourceMapIndex): map_index = bisect.bisect_right(sourcemap_index.offsets, (lineno - 1, colno)) - 1 offset = sourcemap_index.offsets[map_index] col_offset = 0 if lineno != offset[0] else offset[1] state = find_source( sourcemap_index.maps[map_index], lineno - offset[0], colno - col_offset, ) return SourceMap( state.dst_line + offset[0], state.dst_col + col_offset, state.src, state.src_line, state.src_col, state.name ) else: return sourcemap_index.states[bisect.bisect_right(sourcemap_index.keys, (lineno - 1, colno)) - 1]
def _clip(self, keyTS, keyDur, start, stop): ''' Clip the index to a start and stop time. For an index with 10 entries of 10 seconds starting from 0, cliping from 15 to 35 will return the entries 1, 2, and 3. ''' if start >= stop: return None keys = [e[keyTS] for e in self._index] # If the last entry has a duration we add a new entry in the TS list # with the stop time lastEntry = self._index[-1] if lastEntry[keyDur] != -1: keys.append(lastEntry[keyTS] + lastEntry[keyDur]) # Return if the start and stop time are not inside the boundaries if stop <= keys[0] or start >= keys[-1]: return None # Set the start and stop time to match the boundaries so that we don't # get indexes outside the array boundaries if start <= keys[0]: start = keys[0] if stop >= keys[-1]: stop = keys[-1] - 1 # Do the bisection i_start = bisect.bisect_right(keys, start) - 1 i_stop = bisect.bisect_right(keys, stop) return self._index[i_start:i_stop]
def countRangeSum(self, nums, lower, upper): if not nums: return 0 cur, rec = 0, set([0]) for i in range(len(nums)): cur += nums[i] rec.add(cur) s = sorted(rec) c, cur, cnt = [0]*(len(s)+1), 0, 0 def bit_update(pos): while pos<=len(s): c[pos] += 1 pos += pos&(-pos) def bit_sum(pos): res = 0 while pos>0: res += c[pos] pos -= pos&(-pos) return res import bisect bit_update(bisect.bisect_right(s, 0)) for i in range(len(nums)): cur += nums[i] cnt += bit_sum(bisect.bisect_right(s, cur-lower)) cnt -= bit_sum(bisect.bisect_left(s, cur-upper)) bit_update(bisect.bisect_right(s, cur)) return cnt
def __call__(self, sateName="MTSAT-1R", BBox=None): self.Lat = arange(-59.98,59.98+0.00001, 0.04) # fliped order! self.Lon = arange(80.02, 199.98+0.00001, 0.04) self.LatBnd = arange(-60,60+0.00001, 0.04) self.LonBnd = arange(80.0, 200.0+0.00001, 0.04) self.dlat = 0.04 self.dlon = 0.04 self.sateName = sateName self.ny = len(self.Lat) self.nx = len(self.Lon) self.BBox = BBox if BBox !=None: [[lat0,lon0],[lat1,lon1]]= BBox x0 = bisect_right(self.LonBnd, lon0) -1 x1 = bisect_right(self.LonBnd, lon1) -1 y0 = bisect_right(self.LatBnd, lat0) -1 y1 = bisect_right(self.LatBnd, lat1) -1 self.Lon = self.Lon[x0:x1+1] self.Lat = self.Lat[y0:y1+1] self.LonBnd = self.LonBnd[x0:x1+2] self.LatBnd = self.LatBnd[y0:y1+2] self.x0 = x0 self.x1 = x1 self.y0 = y0 self.y1 = y1
def get_worker_intervals(user_entity, register_date, weeks): date_floor = register_date result = [] if user_entity.last_updated is not None: # get end of incomplete fragment as we must finish it last_frag = TagHistory.query(ancestor=user_entity.key, namespace=DS_VERSION).order(-TagHistory.start).get() date_floor = user_entity.last_updated frag_size = get_interval_size(weeks, last_frag.start, last_frag.end) if frag_size < FRAGMENT_SIZE: start_i = bisect.bisect_right(weeks, date_floor) weeks_remaining = FRAGMENT_SIZE - frag_size end_week = weeks[min(len(weeks) - 1, start_i + weeks_remaining - 1)] result.append((weeks[start_i], end_week, last_frag.key.id())) date_floor = end_week # get the first week after 'date_floor' start_i = bisect.bisect_right(weeks, date_floor) for i in xrange(start_i + FRAGMENT_SIZE - 1, len(weeks), FRAGMENT_SIZE): result.append((weeks[i - FRAGMENT_SIZE + 1], weeks[i], None)) remainder = (len(weeks) - start_i) % FRAGMENT_SIZE if remainder > 0: # submit job for last fragment result.append((weeks[len(weeks) - remainder], weeks[-1], None)) return result
def update_blocks(blocks, new_l, new_r, c, d): i_l = bs.bisect_right(blocks, [new_l]) i_r = bs.bisect_right(blocks, [new_r]) #print blocks, i_r, i_l for i in xrange(i_l, i_r): blocks[i][1] += c%md blocks[i][2] += d%md
def count(self, val): """Return the number of occurrences of *val* in the list.""" _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, val) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], val) pos_right = bisect_right(_maxes, val) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], val) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left
def rangeLists(self, fromKey, toKey=None, excludeSmallest=False, excludeLargest=False): "find lists of (keys, values) for keys greater-eq than fromKey and smaller-eq toKey" k = self.keys v = self.values if k is None: (k, v) = self.sortedKeysAndValues() lkeys = len(k) if lkeys < 1: # p "lkeys too small" return ([], []) startIndex = 0 endIndex = lkeys if fromKey is not None: if excludeSmallest: startIndex = bisect.bisect_right(k, fromKey) else: startIndex = bisect.bisect_left(k, fromKey) # p "truncated fromKey", (startIndex, endIndex) if toKey is not None: if excludeLargest: endIndex = bisect.bisect_left(k, toKey) else: endIndex = bisect.bisect_right(k, toKey) result = (k[startIndex:endIndex], v[startIndex:endIndex]) return result
def add(self, val): """Add the element *val* to the list.""" _maxes, _lists, _keys = self._maxes, self._lists, self._keys key = self._key(val) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _maxes[pos] = key _keys[pos].append(key) _lists[pos].append(val) else: idx = bisect_right(_keys[pos], key) _keys[pos].insert(idx, key) _lists[pos].insert(idx, val) self._expand(pos) else: _maxes.append(key) _keys.append([key]) _lists.append([val]) self._len += 1
def kolmogorov_smirnov_two_sample_test(a1, a2=NORMAL, n=1000): """ Returns the likelihood that two independent samples are drawn from the same distribution. Returns a (d, p)-tuple with maximum distance d and two-tailed p-value. By default, the second sample is the normal distribution. """ if a2 == NORMAL: a2 = norm(max(n, len(a1)), mean(a1), stdev(a1)) n1 = float(len(a1)) n2 = float(len(a2)) a1 = sorted(a1) # [1, 2, 5] a2 = sorted(a2) # [3, 4, 6] a3 = a1 + a2 # [1, 2, 5, 3, 4, 6] # Find the indices in a1 so that, # if the values in a3 were inserted before these indices, # the order of a1 would be preserved: cdf1 = [bisect_right(a1, v) for v in a3] # [1, 2, 3, 2, 2, 3] cdf2 = [bisect_right(a2, v) for v in a3] # Cumulative distributions. cdf1 = [v / n1 for v in cdf1] cdf2 = [v / n2 for v in cdf2] # Compute maximum deviation between cumulative distributions. d = max(abs(v1 - v2) for v1, v2 in zip(cdf1, cdf2)) # Compute p-value. e = sqrt(n1 * n2 / (n1 + n2)) p = kolmogorov((e + 0.12 + 0.11 / e) * d) return d, p
def numFriendRequests(self, ages): """ :type ages: List[int] :rtype: int """ ages.sort() def make_range(x): a = (x // 2 + 7 + 1) b = x # [a, b] return a, b ans = 0 for i in range(len(ages)): x = ages[i] a, b = make_range(x) if a > b: continue pa = bisect.bisect_left(ages, a, 0, i) pb = bisect.bisect_right(ages, b, 0, i) pc = bisect.bisect_right(ages, b, i + 1) # print(x, a, b, i, pa, pb, pc) ans += (pb - pa) + (pc - i - 1) return ans
def maxim(self, bh, W=None, N=None): """ Applies a feature reduction filter based on a entropy maximization with linear constratint of W weighet frequency, and N spatial constratint """ if not W == None: self.__W = W if not N == None: self.__N = N patternBank = {} assert isinstance(bh,nii_maths.binnedHistogram), "must pass a BinnedHistogram." offset = bh.precision X = copy.deepcopy(bh.X) Y = copy.deepcopy(bh.Y) exL, exR = (X[0] , X[len(X)-1]) Il = Ir = cusp = math.log(self.__W/float(self.__N)) selL = selR = count = 0 while count < self.__N and not (Il<exL and Ir>exR): Il = Il - offset Ir = Ir + offset i, j = selL, selR = (bisect.bisect_right(X,Il), bisect.bisect_right(X,Ir)) while i < selR and count < self.__N: count += Y[i] patternBank[X[i]] = bh.MAP[X[i]] i += 1 del X[selL:i+1] del Y[selL:i+1] del X del Y self.__patternbank = patternBank return self.__patternbank
def create_grid(atom_coords, x_axis, y_axis, z_axis): """Count atoms in grid boxes defined by passed axes intervals @type atom_coords: list @param atom_coords: A list containing lists of x, y & z coordinates (3 * floats) @type x_axis: numpy array @param x_axis: Array of floats defining the intersection of grid boxes along the x-axis @type y_axis: numpy array @param y_axis: Array of floats defining the intersection of grid boxes along the y-axis @type z_axis: numpy array @param z_axis: Array of floats defining the intersection of grid boxes along the z-axis @rtype: numpy array @return: 3 dimensional array representing the number of atoms in each grid box defined by the input axes divisions """ # Initialize grid # dimension -1 as looking at intervals rather than axes points grid = np.zeros([len(x_axis) - 1, len(y_axis) - 1, len(z_axis) - 1]) # Use a binary search to find which interval each atom coordinate fits in # then increment count in appropriate grid box for atom_coord in atom_coords: x = bisect_right(x_axis, atom_coord[0]) - 1 y = bisect_right(y_axis, atom_coord[1]) - 1 z = bisect_right(z_axis, atom_coord[2]) - 1 grid[x, y, z] += 1 return grid
def getnum(): for c in A: bisect.insort_left(result, c) while len(A) > 0: minvalue = min(A) A.remove(minvalue) tm_ti = time.clock() keypos = bisect.bisect_right(result, minvalue) cp_result = copy.copy(result[keypos:]) tm_ti = time.clock() for c in cp_result: tmp = c | minvalue use_tmp = gmpy2.digits(tmp, 2) use_tmp = "0" * (genroot.prp_num - len(use_tmp)) + use_tmp if (genroot.getsup(use_tmp))[1] < sup_f: continue if tmp == c: continue if tmp >= MAXVALUE: break pos = bisect.bisect_right(result, tmp) if result[pos - 1] != tmp: bisect.insort_left(result, tmp) print("Topology numbers:", len(result), 'used time for sort:%.3f seconds' % (time.clock() - tm_ti))
def find_1(a1, a2, r1, r2, k): n = r1[1] - r1[0] m = r2[1] - r2[0] if n == 0: return a2[r2[0] + k-1] if m == 0: return a1[r1[0] + k-1] # print "Call", r1, r2, k r1, r2, k = Solution.reduce(r1, r2, k) # print "Real", r1, r2, k mid = (r1[0] + r1[1])/2 key = a1[ mid ] b1_l = bi.bisect_left(a1, key, hi = mid+1) b1_r = bi.bisect_right(a1, key, lo = mid) b2_l = bi.bisect_left(a2, key) b2_r = bi.bisect_right(a2, key) b = [[b1_l, b1_r], [b2_l, b2_r]]; # print a1[r1[0]:r1[1]], a2[r2[0]:r2[1]] # print b if b1_l + b2_l >= k + r1[0] + r2[0]: return Solution.find_1(a1, a2, [ r1[0], b1_l ], [ r2[0], b2_l ], k) if b1_r + b2_r >= k + r1[0] + r2[0]: return key k = k-(b1_r - r1[0] + b2_r - r2[0]) return Solution.find_1(a1, a2, [ b1_r, r1[1] ], [ b2_r, r2[1]], k)
def calculate_latencies(self): """ Calculates the latency of each sample for both an input and output spike is available. Returns a list of latency values with an entry for each sample. The latency for samples without a response is set to infinity. """ # Flatten the input and output times and indices tIn, kIn, _ = NetworkInstance.flatten(self["input_times"], self["input_indices"], sort_by_sample=True) tOut, kOut, _ = NetworkInstance.flatten(self["output_times"], self["output_indices"], sort_by_sample=True) # Fetch the number of samples N = self["data_params"]["n_samples"] res = np.zeros(N) # Calculate the latency for each sample for k in xrange(N): # Fetch index of the latest input and output spike time for sample k iInK = bisect.bisect_right(kIn, k) - 1 iOutK = bisect.bisect_right(kOut, k) - 1 # Make sure the returned values are valid and actually refer to the # current sample if iInK < 0 or iOutK < 0 or kIn[iInK] != k or kOut[iOutK] != k: res[k] = np.inf else: res[k] = tOut[iOutK] - tIn[iInK] return res
def add_genome_genes(self, genome_node): self.genome_cnt += 1 internal_ids = [] for gene in genome_node.findall('.//{http://orthoXML.org/2011/}gene'): gene_id = gene.get('id') gene_prot_id = gene.get('protId') try: internal_id = self.valid_id_map[gene_prot_id] self.generef_to_internal_id[int(gene_id)] = internal_id self.internal_to_genome_nr[internal_id] = self.genome_cnt internal_ids.append(internal_id) except KeyError: logger.warning("protId {} of gene(id={}) (in species {}) is not known in this dataset" .format(gene_prot_id, gene_id, genome_node.get('name'))) min_id = min(internal_ids) - 1 max_id = max(internal_ids) - 1 k_min = bisect_right(self.internal_genome_offs, min_id) k_max = bisect_right(self.internal_genome_offs, max_id) if k_min != k_max: cnts = collections.Counter( (self.species_order[bisect_right(self.internal_genome_offs, int_id-1) - 1] for int_id in internal_ids)).most_common() logger.error("Not all crossreferences used in species '{}' map to the same species: {}" .format(genome_node.get('name'), cnts)) return False return True
def find_grid(self, pts, box = False): # calculate grid xstart = bisect_right(self.x, min(pts[0]))-1 xend = bisect_left(self.x, max(pts[0])) ystart = bisect_right(self.y, min(pts[1]))-1 yend = bisect_left(self.y, max(pts[1])) zstart = bisect_right(self.z, min(pts[2]))-1 zend = bisect_left(self.z, max(pts[2])) # if need start and end to be different (box = true) add one to end if box: if xstart == xend: if xend == (len(self.x)-1): xstart -= 1 else: xend += 1 if ystart == yend: if yend == (len(self.y)-1): ystart -= 1 else: yend += 1 if zstart == zend: if zend == (len(self.z)-1): zstart -= 1 else: zend += 1 return [[xstart, xend], [ystart, yend], [zstart, zend]]
def draw_cdf(data, ls, lg): sorted_data = np.sort(data) yvals = np.arange(len(sorted_data))/float(len(sorted_data)) ## Count the percent of session crashes gt_zero_ind = bisect.bisect_right(sorted_data, 0) gt_zero_percent = yvals[gt_zero_ind] print "{0:.0f}%".format(gt_zero_percent * 100), " crashed sessions for method ", lg ## Count the 80% of user QoE gt_tenpercent_ind = bisect.bisect_right(yvals, 0.2) gt_tenpercent_qoe = sorted_data[gt_tenpercent_ind] print "80-percentile QoE is ", str(gt_tenpercent_qoe), " for method: ", lg ## Count the 90% of user QoE gt_tenpercent_ind = bisect.bisect_right(yvals, 0.1) gt_tenpercent_qoe = sorted_data[gt_tenpercent_ind] print "90-percentile QoE is ", str(gt_tenpercent_qoe), " for method: ", lg ## Count the 95% of user QoE gt_tenpercent_ind = bisect.bisect_right(yvals, 0.05) gt_tenpercent_qoe = sorted_data[gt_tenpercent_ind] print "95-percentile QoE is ", str(gt_tenpercent_qoe), " for method: ", lg plt.plot(sorted_data, yvals, ls, label=lg, linewidth=2.0)
def get_objects(entity_start, entity_end): """ Return objects we have to check collision for at the very moment. For this, the object has to meet one of the following conditions # 1 obj_start < entity_start and entity_end < object_end (obj is longer than entity) # 2 obj_end is withing entity positions # 3 obj_start is within entity positions Runtime atm: O(log n + k) where n = number of objects and k = number of objects found for detection TODO: We need a more elaborate algorithm here, currently it's possible that monsters which are not near enough to the player go through obstacles ;) """ min_x = entity_start - collision_span max_x = entity_end + collision_span start_left = bisect.bisect_left(object_starts, (min_x,)) start_right = bisect.bisect_right(object_starts, (max_x,)) end_left = bisect.bisect_left(object_ends, (min_x,)) end_right = bisect.bisect_right(object_ends, (max_x,)) objects = [] for obj in object_starts[start_left:end_right]: objects.append(obj[1:]) for obj in object_ends[end_left:end_right]: objects.append(obj[1:]) return objects + object_ubiquitous
def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ if self.toSort: self.numbers.sort() self.toSort = False if len(self.numbers) < 2 \ or value < self.numbers[0] + self.numbers[1] \ or value > self.numbers[-1] + self.numbers[-2]: return False index1 = 0 index2 = bisect.bisect_right(self.numbers, value - self.numbers[0]) - 1 odd_flag = True while True: if self.numbers[index1] + self.numbers[index2] != value: if index2 - index1 <= 1: return False if odd_flag: index1 = bisect.bisect_left(self.numbers, value - self.numbers[index2], index1+1, index2) else: index2 = bisect.bisect_right(self.numbers, value - self.numbers[index1], index1+1, index2) - 1 odd_flag = not odd_flag else: return True
def sweepB(best, worst, front): """Adjust the rank number of the worst fitnesses according to the best fitnesses on the first two objectives using a sweep procedure. """ stairs, fstairs = [], [] iter_best = iter(best) next_best = next(iter_best, False) for h in worst: while next_best and h[:2] <= next_best[:2]: insert = True for i, fstair in enumerate(fstairs): if front[fstair] == front[next_best]: if fstair[1] > next_best[1]: insert = False else: del stairs[i], fstairs[i] break if insert: idx = bisect.bisect_right(stairs, -next_best[1]) stairs.insert(idx, -next_best[1]) fstairs.insert(idx, next_best) next_best = next(iter_best, False) idx = bisect.bisect_right(stairs, -h[1]) if 0 < idx <= len(stairs): fstair = max(fstairs[:idx], key=front.__getitem__) front[h] = max(front[h], front[fstair]+1)
def empHistory2(history,a,b,c,d,html): times = history.keys() ainterval = times[bisect.bisect_left(times,a):bisect.bisect_right(times,b)] binterval = times[bisect.bisect_left(times,c):bisect.bisect_right(times,d)] amatches = set() bmatches = set() for t in ainterval: l = history[t] for i in l: if i.isGuest == False: amatches.add(i.name) for t in binterval: l = history[t] for i in l: if i.isGuest == False: bmatches.add(i.name) matches = set() for t in amatches: if t not in bmatches: matches.add(t) matcheslist = list(matches) matcheslist.sort() if html == True: t = "<html><body><table><tr><th>Employees</th></tr>" t = t + "".join(["<tr><td>%s</td></tr>\n" % i for i in matcheslist]) t = t + "</table></body></html>" return t else: return ",".join(matcheslist)
def filter_a_chrom(chrom, oriPeaks, subPeaks, chromWig, args): ''' Filters a chromsome oriPeaks and subPeaks are lists of peaks from the same chromosome. Both peak lists are sorted by coordinates on the chromosome. ''' sub_peak_starts = [k[1] for k in subPeaks] result = [] for op in oriPeaks: startIdx = bisect.bisect_left( chromWig[:,0], op[1] ) endIdx = bisect.bisect_right( chromWig[:,0], op[2] ) subStartIdx = bisect.bisect_left( sub_peak_starts, op[1] ) subEndIdx = bisect.bisect_right( sub_peak_starts, op[2] ) if endIdx <= startIdx or subEndIdx <= subStartIdx: continue currWig = wig.expandWig( chromWig[startIdx:endIdx,:],0, 1, smooth=False ) startPos = chromWig[ startIdx, 0 ] endPos = chromWig[ endIdx - 1, 0 ] maxV = np.max( currWig ) #The maximum value for subI in range( subStartIdx, subEndIdx ): relStart = max( 0, subPeaks[ subI ][1] - startPos ) relEnd = min( currWig.shape[0] - 1, subPeaks[ subI ][2] - startPos ) subMaxV = np.max( currWig[ relStart: relEnd ] ) if subMaxV > args.threshfrac * maxV and subMaxV > args.cutoff: result.append( subPeaks[ subI ] ) result[-1][4] = subMaxV result[-1][5] = args.strand return result
def main(): text_name = 'corpus.txt' with open(text_name, 'r') as f: word_list = f.read().split() frequencies = defaultdict(list) for i, w in enumerate(word_list): frequencies[w].append(i) ordered_list = Counter(word_list).most_common() N = int(raw_input()) for case_num in range(1, N+1): A, B = map(int, raw_input().split()) occurrences = Counter() for word, frequency in ordered_list: if occurrences and frequency <= occurrences.most_common()[-1][1]: break # Binary search num_occurrences = (bisect.bisect_right(frequencies[word],B-1) - bisect.bisect_right(frequencies[word],A-2)) occurrences[word] = num_occurrences if len(occurrences) > 3: del occurrences[occurrences.most_common()[-1][0]] top_frequent = occurrences.most_common() string_frequent = [' '.join(map(str, frequent)) for frequent in top_frequent] print 'Case #%d: %s' % (case_num, ','.join(string_frequent))
def raise_wall(wall, wallh, w, e, s): # print wall, wallh # print w, e, s a = bisect.bisect_right(wall, w) if a > 0: a -= 1 b = bisect.bisect_right(wall, e) print a, b insert = False if wall[a] < w and wallh[a] < s: wall.insert(a + 1, w) wallh.insert(a + 1, s) b += 1 insert = True elif wall[a] == w and wallh[a] < s: wallh[a] = s insert = True if insert: if b >= len(wall): wall.insert(a + 2, e) wallh.insert(a + 2, 0) elif wall[b] > e: wall.insert(a + 2, e) wallh.insert(a + 2, wall[b]) for i in xrange(a + 2, b): if wallh[i] < s: del(wall[i]) del(wallh[i])
def insert (self,x1,x2,y1,y2,color): x1,x2,y1,y2 = self.format(x1,self.width),self.format(x2,self.width),self.format(y1,self.height),self.format(y2,self.height) a1 = bisect_right(self.x,x1) a2 = bisect_right(self.x,x2) insert_x1 = x1!=self.x[a1-1] insert_x2 = x2!=self.x[a2-1] b1 = bisect_right(self.y,y1) b2 = bisect_right(self.y,y2) insert_y1 = y1!=self.y[b1-1] insert_y2 = y2!=self.y[b2-1] colors = self.colors.copy() for i in self.x[1:]: if insert_y1: colors[(i,y1)] = self.colors[(i,self.y[b1])] if insert_y2: colors[(i,y2)] = self.colors[(i,self.y[b2])] for j in self.y[1:]: if insert_x1: colors[(x1,j)] = self.colors[(self.x[a1],j)] if insert_x2: colors[(x2,j)] = self.colors[(self.x[a2],j)] if insert_x1 and insert_y1: colors[(x1,y1)] = self.colors[(self.x[a1],self.y[b1])] if insert_x1 and insert_y2: colors[(x1,y2)] = self.colors[(self.x[a1],self.y[b2])] if insert_x2 and insert_y1: colors[(x2,y1)] = self.colors[(self.x[a2],self.y[b1])] if insert_x2 and insert_y2: colors[(x2,y2)] = self.colors[(self.x[a2],self.y[b2])] if insert_x1: self.x.insert(a1,x1) if insert_x2: self.x.insert(a2+(1 if insert_x1 else 0),x2) if insert_y1: self.y.insert(b1,y1) if insert_y2: self.y.insert(b2+(1 if insert_y1 else 0),y2) for i in self.x[1:]: for j in self.y[1:]: if x1<i<=x2 and y1<j<=y2: colors[(i,j)] = color self.colors = colors
def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ sums=nums[:] #print(sums) for i in range(1,len(sums)): sums[i]+=sums[i-1] sorted_sums=sorted(set(sums)) #print(sums) #print(sorted_sums) tree=FenwickTree(len(sorted_sums)) import bisect ret=0 for s in sums: left=bisect.bisect_left(sorted_sums,s-upper) right=bisect.bisect_right(sorted_sums,s-lower) #print('left,right',left,right) ret+=tree.sum(right) - tree.sum(left) if s>=lower and s<=upper: ret+=1 #print('add position',bisect.bisect_right(sorted_sums,s)) tree.add(bisect.bisect_right(sorted_sums,s),1) return ret
def wall_minimum_height(wall, wallh, w, e): a = bisect.bisect_right(wall, w) - 1 if a < 0: a = 0 b = bisect.bisect_right(wall, e) if a == b: return 0 return min(wallh[a:b])
def test_bisect_right(self): self.assertEqual(mybisect.bisect_right(self.sample, 0), bisect.bisect_right(self.sample, 0)) self.assertEqual(mybisect.bisect_right(self.sample, 5), bisect.bisect_right(self.sample, 5)) self.assertEqual(mybisect.bisect_right(self.sample, 7), bisect.bisect_right(self.sample, 7)) self.assertEqual(mybisect.bisect_right(self.sample, 10), bisect.bisect_right(self.sample, 10))
https://www.acmicpc.net/problem/2467 Using binary search """ #1. My Solution import sys import bisect input = sys.stdin.readline n = int(input().strip()) arr = [*map(int, input().strip().split())] val = sys.maxsize acid = 0 base = 0 for i, a in enumerate(arr): j = bisect.bisect_right(arr, -a) if j == n: b = arr[j - 1] if a != arr[j - 1] else arr[j - 2] temp = abs(a + b) elif j == 0: b = arr[j] if a != arr[j] else arr[j + 1] temp = abs(a + b) else: b = arr[j - 1] if a != arr[j - 1] else arr[j - 2] c = arr[j] if a != arr[j] else arr[j + 1] if abs(a + b) > abs(a + c): b = c temp = abs(a + c) else: temp = abs(a + b)
def count_by_number(array, target): right_index = bisect_right(array, target) left_index = bisect_left(array, target) return right_index - left_index
import bisect A, B, Q = map(int, input().split()) INF = 10**12 s_list = [-INF] + [int(input()) for _ in range(A)] + [INF] t_list = [-INF] + [int(input()) for _ in range(B)] + [INF] for _ in range(Q): x = int(input()) s_right_index = bisect.bisect_right(s_list, x) s_right = s_list[s_right_index] s_left = s_list[s_right_index - 1] t_right_index = bisect.bisect_right(t_list, x) t_right = t_list[t_right_index] t_left = t_list[t_right_index - 1] dist = INF for s in [s_right, s_left]: for t in [t_right, t_left]: dist = min(dist, abs(s - t) + abs(s - x), abs(t - s) + abs(t - x)) print(dist)
from bisect import bisect_left, bisect_right a = [3, 5, 7, 9] print(bisect_left(a, 2)) # 0 print(bisect_right(a, 2)) # 0 print(bisect_left(a, 3)) # 0 print(bisect_right(a, 3)) # 1 print(bisect_left(a, 4)) # 1 print(bisect_right(a, 4)) # 1 print(bisect_left(a, 9)) # 3 print(bisect_right(a, 9)) # 4 print(bisect_left(a, 10)) # 4 print(bisect_right(a, 10)) # 4
def find_imprint(ts): logging.debug('Finding imprint for ts = {}'.format(ts)) keys = [r[0] for r in DATA] x = bisect.bisect_right(keys, ts) return x
def histogram(request, pks=None): """ view for numeric polls """ all_polls = Poll.objects.filter(type=u'n') pks = (pks if pks != None else request.GET.get('pks', None)) if pks: items = 6 polls = retrieve_poll(request, pks) responses = Response.objects.filter(poll__in=polls) pks = polls.values_list('pk', flat=True) responses = Response.objects.filter(poll__in=polls, poll__type=u'n') plottable_data = {} if responses: poll_results = {} poll_qns = [ 'Qn:' + poll.question + '<br>' for poll in Poll.objects.filter(pk__in=pks) ] total_responses = responses.count() vals_list = \ Value.objects.filter(entity_id__in=responses).values_list('value_float' , flat=True) vals_list = sorted(vals_list) max = int(vals_list[-1]) min = int(vals_list[0]) num_list = range(min, max) increment = int(max / items) bounds = num_list[::increment] ranges_list = [ str(a) + '-' + str(a + increment) for a in bounds if a < max ] poll_results['categories'] = ranges_list poll_results['title'] = poll_qns for response in responses: name = response.poll.name poll_results.setdefault(name, {}) poll_results[name].setdefault('data', {}) if len(response.eav_values.all()) > 0: value = \ int(response.eav_values.all()[0].value_float) pos = bisect.bisect_right(bounds, value) - 1 r = ranges_list[pos] poll_results[name]['data'].setdefault(r, 0) poll_results[name]['data'][r] += 1 data = [] for key in poll_results.keys(): if key not in ['categories', 'title']: d = {} d['name'] = key d['data'] = poll_results[key]['data'].values() data.append(d) plottable_data['data'] = data plottable_data['title'] = poll_qns plottable_data['categories'] = ranges_list plottable_data['mean'] = sum(vals_list) / len(vals_list) plottable_data['median'] = vals_list[len(vals_list) / 2] return HttpResponse(mark_safe(simplejson.dumps(plottable_data))) return render_to_response('ureport/partials/viz/histogram.html', {'polls': all_polls}, context_instance=RequestContext(request))
def get(self, key: str, timestamp: int) -> str: if key not in self.kv or timestamp < self.kt[key][0]: return '' pos = bisect.bisect_right(self.kt[key], timestamp) - 1 return self.kv[key][pos]
def localize(self, dt, is_dst=False): '''Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. is_dst is used to determine the correct timezone in the ambigous period at the end of daylight saving time. >>> from pytz import timezone >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> amdam = timezone('Europe/Amsterdam') >>> dt = datetime(2004, 10, 31, 2, 0, 0) >>> loc_dt1 = amdam.localize(dt, is_dst=True) >>> loc_dt2 = amdam.localize(dt, is_dst=False) >>> loc_dt1.strftime(fmt) '2004-10-31 02:00:00 CEST (+0200)' >>> loc_dt2.strftime(fmt) '2004-10-31 02:00:00 CET (+0100)' >>> str(loc_dt2 - loc_dt1) '1:00:00' Use is_dst=None to raise an AmbiguousTimeError for ambiguous times at the end of daylight saving time >>> try: ... loc_dt1 = amdam.localize(dt, is_dst=None) ... except AmbiguousTimeError: ... print('Ambiguous') Ambiguous is_dst defaults to False >>> amdam.localize(dt) == amdam.localize(dt, False) True is_dst is also used to determine the correct timezone in the wallclock times jumped over at the start of daylight saving time. >>> pacific = timezone('US/Pacific') >>> dt = datetime(2008, 3, 9, 2, 0, 0) >>> ploc_dt1 = pacific.localize(dt, is_dst=True) >>> ploc_dt2 = pacific.localize(dt, is_dst=False) >>> ploc_dt1.strftime(fmt) '2008-03-09 02:00:00 PDT (-0700)' >>> ploc_dt2.strftime(fmt) '2008-03-09 02:00:00 PST (-0800)' >>> str(ploc_dt2 - ploc_dt1) '1:00:00' Use is_dst=None to raise a NonExistentTimeError for these skipped times. >>> try: ... loc_dt1 = pacific.localize(dt, is_dst=None) ... except NonExistentTimeError: ... print('Non-existent') Non-existent ''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') # Find the two best possibilities. possible_loc_dt = set() for delta in [timedelta(days=-1), timedelta(days=1)]: loc_dt = dt + delta idx = max(0, bisect_right(self._utc_transition_times, loc_dt) - 1) inf = self._transition_info[idx] tzinfo = self._tzinfos[inf] loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo)) if loc_dt.replace(tzinfo=None) == dt: possible_loc_dt.add(loc_dt) if len(possible_loc_dt) == 1: return possible_loc_dt.pop() # If there are no possibly correct timezones, we are attempting # to convert a time that never happened - the time period jumped # during the start-of-DST transition period. if len(possible_loc_dt) == 0: # If we refuse to guess, raise an exception. if is_dst is None: raise NonExistentTimeError(dt) # If we are forcing the pre-DST side of the DST transition, we # obtain the correct timezone by winding the clock forward a few # hours. elif is_dst: return self.localize(dt + timedelta(hours=6), is_dst=True) - timedelta(hours=6) # If we are forcing the post-DST side of the DST transition, we # obtain the correct timezone by winding the clock back. else: return self.localize(dt - timedelta(hours=6), is_dst=False) + timedelta(hours=6) # If we get this far, we have multiple possible timezones - this # is an ambiguous case occuring during the end-of-DST transition. # If told to be strict, raise an exception since we have an # ambiguous case if is_dst is None: raise AmbiguousTimeError(dt) # Filter out the possiblilities that don't match the requested # is_dst filtered_possible_loc_dt = [ p for p in possible_loc_dt if bool(p.tzinfo._dst) == is_dst ] # Hopefully we only have one possibility left. Return it. if len(filtered_possible_loc_dt) == 1: return filtered_possible_loc_dt[0] if len(filtered_possible_loc_dt) == 0: filtered_possible_loc_dt = list(possible_loc_dt) # If we get this far, we have in a wierd timezone transition # where the clocks have been wound back but is_dst is the same # in both (eg. Europe/Warsaw 1915 when they switched to CET). # At this point, we just have to guess unless we allow more # hints to be passed in (such as the UTC offset or abbreviation), # but that is just getting silly. # # Choose the earliest (by UTC) applicable timezone if is_dst=True # Choose the latest (by UTC) applicable timezone if is_dst=False # i.e., behave like end-of-DST transition dates = {} # utc -> local for local_dt in filtered_possible_loc_dt: utc_time = local_dt.replace( tzinfo=None) - local_dt.tzinfo._utcoffset assert utc_time not in dates dates[utc_time] = local_dt return dates[[min, max][not is_dst](dates)]
#coding: utf-8 import math import heapq import bisect import numpy as np from collections import Counter #from scipy.misc import comb N = int(input()) A = list(map(int, input().split())) A.sort() B = list(map(int, input().split())) B.sort() C = list(map(int, input().split())) C.sort() ans = 0 for b in B: a_cnt = bisect.bisect_left(A, b) c_cnt = N - bisect.bisect_right(C, b) ans += a_cnt * c_cnt print(ans)
# Autor: Felipe Souza Dias<*****@*****.**> # Nome: Quantos Fibs? # Nível: 3 # Categoria: MATEMÁTICA # URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1722 import bisect fib = [1, 2] for i in range(2, 1000): fib.append(fib[i - 1] + fib[i - 2]) a, b = map(int, input().split(' ')) while a != 0 or b != 0: lb = bisect.bisect_left(fib, a) up = bisect.bisect_right(fib, b) print(up - lb) a, b = map(int, input().split(' '))
def _quantize(x, bins): return list(map(lambda y: bisect.bisect_right(sorted(bins), y), x))
def write_hex_file(self, f, write_start_addr=True): """Write data to file f in HEX format. @param f filename or file-like object for writing @param write_start_addr enable or disable writing start address record to file (enabled by default). If there is no start address in obj, nothing will be written regardless of this setting. """ fwrite = getattr(f, "write", None) if fwrite: fobj = f fclose = None else: fobj = open(f, 'w') fwrite = fobj.write fclose = fobj.close # Translation table for uppercasing hex ascii string. # timeit shows that using hexstr.translate(table) # is faster than hexstr.upper(): # 0.452ms vs. 0.652ms (translate vs. upper) if sys.version_info[0] >= 3: table = bytes(range(256)).upper() else: table = ''.join(chr(i).upper() for i in range(256)) # start address record if any if self.start_addr and write_start_addr: keys = self.start_addr.keys() keys.sort() bin = array('B', asbytes('\0' * 9)) if keys == ['CS', 'IP']: # Start Segment Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 3 # rectyp cs = self.start_addr['CS'] bin[4] = (cs >> 8) & 0x0FF bin[5] = cs & 0x0FF ip = self.start_addr['IP'] bin[6] = (ip >> 8) & 0x0FF bin[7] = ip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') elif keys == ['EIP']: # Start Linear Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 5 # rectyp eip = self.start_addr['EIP'] bin[4] = (eip >> 24) & 0x0FF bin[5] = (eip >> 16) & 0x0FF bin[6] = (eip >> 8) & 0x0FF bin[7] = eip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') else: if fclose: fclose() raise InvalidStartAddressValueError(start_addr=self.start_addr) # data addresses = self._buf.keys() addresses.sort() addr_len = len(addresses) if addr_len: minaddr = addresses[0] maxaddr = addresses[-1] if maxaddr > 65535: need_offset_record = True else: need_offset_record = False high_ofs = 0 cur_addr = minaddr cur_ix = 0 while cur_addr <= maxaddr: if need_offset_record: bin = array('B', asbytes('\0' * 7)) bin[0] = 2 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 4 # rectyp high_ofs = int(cur_addr >> 16) b = divmod(high_ofs, 256) bin[4] = b[0] # msb of high_ofs bin[5] = b[1] # lsb of high_ofs bin[6] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') while True: # produce one record low_addr = cur_addr & 0x0FFFF # chain_len off by 1 chain_len = min(15, 65535 - low_addr, maxaddr - cur_addr) # search continuous chain stop_addr = cur_addr + chain_len if chain_len: ix = bisect_right( addresses, stop_addr, cur_ix, min(cur_ix + chain_len + 1, addr_len)) chain_len = ix - cur_ix # real chain_len # there could be small holes in the chain # but we will catch them by try-except later # so for big continuous files we will work # at maximum possible speed else: chain_len = 1 # real chain_len bin = array('B', asbytes('\0' * (5 + chain_len))) b = divmod(low_addr, 256) bin[1] = b[0] # msb of low_addr bin[2] = b[1] # lsb of low_addr bin[3] = 0 # rectype try: # if there is small holes we'll catch them for i in range(chain_len): bin[4 + i] = self._buf[cur_addr + i] except KeyError: # we catch a hole so we should shrink the chain chain_len = i bin = bin[:5 + i] bin[0] = chain_len bin[4 + chain_len] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + asstr(hexlify(bin.tostring()).translate(table)) + '\n') # adjust cur_addr/cur_ix cur_ix += chain_len if cur_ix < addr_len: cur_addr = addresses[cur_ix] else: cur_addr = maxaddr + 1 break high_addr = int(cur_addr >> 16) if high_addr > high_ofs: break # end-of-file record fwrite(":00000001FF\n") if fclose: fclose()
def get_lr(self, epoch): section = bisect_right(self.milestones, epoch) periods = [self.base_lr] + self.gammas return periods[section]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- N,M,K = map(int,input().split()) A = list(map(int,input().split())) B = list(map(int,input().split())) sumAt = [0] sumBt = [0] for a in A: sumAt.append(sumAt[-1]+a) for b in B: sumBt.append(sumBt[-1]+b) WA = sumAt WB = sumBt[1::] ans = 0 import bisect for ai,a in enumerate(WA): if K < a: break t = K-a bi = bisect.bisect_right(WB,t) if ans < ai+bi: ans = ai+bi print (ans)
def count_by_range(array, left_value, right_value): right_index = bisect_right(array, right_value) left_index = bisect_left(array, left_value) return right_index - left_index
def get_lr(self, epoch): section = bisect_right(self.milestones, epoch) return self.base_lr * np.prod(self.gammas[:section])
def find_gt_index(self, k): 'Return index of first item with a key > k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i != len(self): return i raise ValueError('No item found with key above: %r' % (k, ))
import bisect N, M, K = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) Ac = [0] * (N + 1) Bc = [0] * (M + 1) for i in range(1, N + 1): Ac[i] = Ac[i - 1] + A[i - 1] for j in range(1, M + 1): Bc[j] = Bc[j - 1] + B[j - 1] ans = 0 for i in range(N + 1): n = K - Ac[i] if n < 0: break tmp = bisect.bisect_right(Bc, n) - 1 ans = max(ans, i + tmp) #print(i, tmp, ans, n, Ac, Bc) print(ans)
def insert_right(self, item): 'Insert a new item. If equal keys are found, add to the right' k = self._key(item) i = bisect_right(self._keys, k) self._keys.insert(i, k) self._items.insert(i, item)
def find_le_index(self, k): 'Return index of last item with a key <= k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i: return i - 1 raise ValueError('No item found with key at or below: %r' % (k, ))
def index(self, item): 'Find the position of an item. Raise ValueError if not found.' k = self._key(item) i = bisect_left(self._keys, k) j = bisect_right(self._keys, k) return self._items[i:j].index(item) + i
def count(self, item): 'Return number of occurrences of item' k = self._key(item) i = bisect_left(self._keys, k) j = bisect_right(self._keys, k) return self._items[i:j].count(item)
ri = lambda: int(input()) rl = lambda: list(map(int, input().split())) rr = lambda N: [ri() for _ in range(N)] YN = lambda b: print('YES') if b else print('NO') yn = lambda b: print('Yes') if b else print('No') OE = lambda x: print('Odd') if x % 2 else print('Even') INF = 10**18 MOD = 10**9 + 7 N, X = rl() S = rl() S.sort() import bisect cnt_0 = bisect.bisect_right(S, X) def search(s, n, x): print(s, n, x) if n == 1: return x % S[0] ret = 0 for i in range(n): res = 0 x_ = x % s[i] ind = bisect.bisect_right(S, x_) if ind == 0: res = x_ else: res = search(S[:ind], ind, x_) for j in range(n - ind, n + 1):
def __contains__(self, item): k = self._key(item) i = bisect_left(self._keys, k) j = bisect_right(self._keys, k) return item in self._items[i:j]
def retrieve(self, s: str, e: str, gra: str) -> 'List[int]': idx = self.gra_idx[gra] lo = bisect.bisect_left(self.logs, (s[:idx] + self.start[idx:], 0)) hi = bisect.bisect_right(self.logs, (e[:idx] + self.end[idx:], 300)) return [log[1] for log in self.logs[lo:hi]]
def _quantize(x, bins): bins = copy.copy(bins) bins = sorted(bins) quantized = list(map(lambda y: bisect.bisect_right(bins, y), x)) return quantized
from bisect import bisect_left, bisect_right n = int(input()) arr1 = list(map(int, input().split())) m = int(input()) arr2 = list(map(int, input().split())) arr1.sort() for data in arr2: print(bisect_right(arr1, data) - bisect_left(arr1, data), end=' ')
def find_gt(lst, item): # find leftmost value greater than item i = bisect.bisect_right(lst, item) return i, lst[i]
plt.grid() parity = [(R * s * C) / F * 100 for s in allData[1]['S'] if (R * s * C) / F < 2] x = [s for s in allData[0]['S'] if s < 100] parity = x plt.plot(parity, allData[0]['V'][:len(parity)], label=r'American Option Embedded Put', linewidth=2) plt.plot(parity, allData[1]['V'][:len(parity)], label=r'Embedded Put Removed', linewidth=2, linestyle='--') equity = [max(95., 2. * s) for s in allData[1]['S']] lessC = bisect_right(allData[0]['V'], 100) plt.annotate(r'$V(S_0=%.2f,t=0)=P_p$' % (parity[lessC]), xy=(parity[lessC], allData[0]['V'][lessC]), xytext=(22, 160), arrowprops=dict(arrowstyle="->")) lessRS = 0 for i in allData[0]['V']: if (allData[1]['S'][lessRS] * R >= i): break lessRS += 1 plt.annotate(r'$V(S_0=%.2f,t=0)=RS_0$' % (parity[lessRS]), xy=(parity[lessRS], allData[0]['V'][lessRS]), xytext=(65, 100), arrowprops=dict(arrowstyle="->")) plt.plot(allData[1]['S'][:len(parity)], equity[:len(parity)],
def bisect_right(a, x): def func(i): return x < a[i] return meguru_bisect(-1, len(a), func) class TestBisect(unittest.TestCase): def test_bisect(self): test_patterns = [ ([2, 3, 4, 4, 5, 6], 6), ([], 6), ([3, 3], 0), ([3, 3], 6), ] for a, x in test_patterns: with self.subTest(a=a, x=x): self.assertEqual(bisect_left(a, x), bisect.bisect_left(a, x)) with self.subTest(a=a, x=x): self.assertEqual(bisect_right(a, x), bisect.bisect_right(a, x)) if __name__ == '__main__': a = [2, 3, 4, 4, 5, 6] x = 6 print(bisect_left(a, x)) print(bisect.bisect_left(a, x)) print(bisect_right(a, x)) print(bisect.bisect_right(a, x))