def index(self, xval): """ Locates the index of the specified x value in the object's x list. :param float xval: The x value to locate in the list. :return: The integer index for the x value in the x list. :rtype: int **Notes** If the *empty* keyword argument is True, the index will be located using the bisect module. If the x value is not in the current x list, the appropriate insertion index is returned. If the *empty* keyword argument is False, the index will be calculated based on the ``start`` and ``decpl`` values of the object (this is more computationally efficient than bisection). """ if xval > self.end or xval < self.start: raise ValueError( f'The x value {xval} is outside of the x-list range of this {self.__class__.__name__} instance ' f'({self.start}, {self.end}).' ) if self.empty is True: # if spectrum is unfilled, searching is required return bl(self.x, round(xval, self.decpl)) else: # otherwise, calculation of the index is more efficient return int( round( # round after multiplication (xval - self.start) * (10 ** self.decpl) # calculate index location ) )
def localmax(x,y,xval,lookwithin=1): """finds the local maximum within +/- lookwithin of the xval""" l,r = bl(x,xval-lookwithin),br(x,xval+lookwithin) try: return max(y[l:r]) except ValueError: raise ValueError("No maximum value found in range, perhaps wrong window region?")
def estimatedem(x,y,em,simmin,simmax,lookwithin=1): """estimates the exact mass of a peak""" l,r = bl(x,simmin-lookwithin),br(x,simmax+lookwithin) # narrow range to that of the isotope pattern locmax = max(y[l:r]) # find local max in that range for ind,val in enumerate(y): if val == locmax: # if the y-value equals the local max if ind >= l and ind <= r: # and if the index is in the range (avoids false locations) return x[ind] difleft = abs(em-simmin) difright = abs(em-simmax) return '>%.1f' %max(difleft,difright) # if no match is found, return maximum difference
def find(seq, first, last, largest): h, ls = 0, len(seq) for i in range(ls): for j in range(1, largest+1): if i+j > ls: break sub = seq[i:i+j] if sub not in subs: break if sub not in genesMap: continue index, hs = genesMap[sub] h += hs[br(index, last)]-hs[bl(index, first)] return h
def main(): N = INT() # 2 次元リストを x[0] で昇順にソート, x[0] が同じ場合は x[1] で降順にソート. WH = sorted([list(MAP()) for _ in range(N)], key=(lambda x: (x[0], -x[1]))) present = [WH[0][1]] # プレゼントの短辺の長さを昇順に格納 for _, h in WH[1:]: if h > present[-1]: present.append(h) else: present[bl(present, h)] = h # w の長さが一つ前と同じなら, h が短いほうに置き換える. print(len(present))
def fallingSquares(self, positions: List[List[int]]) -> List[int]: ans, xs, hs = [], [0], [0] for (x, h) in positions: i, j = br(xs, x), bl(xs, x + h) H = max(hs[max(i - 1, 0):j], default=0) + h xs[i:j] = [x, x + h] hs[i:j] = [H, hs[j - 1]] ans.append(H) if len(ans) > 1: ans[-1] = max(ans[-1], ans[-2]) return ans
def test_random(): from bisect import bisect_left as bl, bisect_right as br import random for _ in range(500): array = [random.randint(1, 20) for _ in range(random.randint(1, 100))] array.sort() for _ in range(100): x = random.randint(-5, 25) assert bisect_left(array, x) == bl(array, x) assert bisect_right(array, x) == br(array, x)
def main(): N = INT() li = [] for i in range(N): w = INT() w_index = bl(li, w) if w_index == len(li): li.append(w) # w の挿入箇所が丁度 li の後ろの時, li にアペンド else: li[w_index] = w # 要素の 1 つを w で置き換え (li の要素の総和が小さくなるように) print(len(li))
def medianSlidingWindow(self, nums, k): part = sorted(nums[:k - 1]) res = [] for i in range(k - 1, len(nums)): if i >= k: part.pop(bl(part, nums[i - k])) insort(part, nums[i]) med = part[k // 2] if k & 1 else (part[k // 2] + part[k // 2 - 1]) / 2.0 res.append(med) return res
def removeRange(self, left, right): ivs = self.ivs ilo, ihi = bl(ivs, left), br(ivs, right) new = [] if ilo % 2 == 1: ilo -= 1 new += [ivs[ilo], left] if ihi % 2 == 1: new += [right, ivs[ihi]] ihi += 1 self.ivs = ivs[:ilo] + new + ivs[ihi:]
def retrieve(self, s0: str, e0: str, gra: str) -> List[int]: s, e = parse(s0, gra), parse(e0, gra, roundUp=True) left = bl(self.logs, (s, 0)) right = br(self.logs, (e, float("inf"))) ans = [x[1] for x in self.logs[left:right]] return ans # Your LogSystem object will be instantiated and called as such: # obj = LogSystem() # obj.put(id,timestamp) # param_2 = obj.retrieve(s,e,gra)
def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ idx1 = bl(nums, target) idx2 = br(nums, target) print idx1, idx2 idx1 = idx1 if idx1 < len(nums) and nums[idx1] == target else -1 idx2 = idx2 - 1 if idx2 and nums[idx2 - 1] == target else -1 return [idx1, idx2]
def addRange(self, left, right): # Get the left most index to insert left # And the right most index to insert right # This will include everyrange inside [left,right) # we replace everything form i:j with new range # If i is starting a new range, then we can insert left at i # if j is starting a new range, it is the closing range of i # if j in not starting a new range, use exiting closing range # if i is not starting a new range, but j is, then update range at j to right i, j = bl(self._X, left), br(self._X, right) self._X[i:j] = [left]*(i%2 == 0) + [right]*(j%2 == 0)
def solution(): ans = set() visited = [1] * n for i in range(n): if visited[i]: visited[i] = 0 idx = bl(arr, x - arr[i]) if idx >= n or arr[i] == arr[idx] or arr[i] + arr[idx] != x: continue visited[idx] = 0 ans.add((arr[i], arr[idx])) print(len(ans))
def lengthOfLIS(nums: [int]) -> int: """ O(N log N) Return the length of longest increasing subsequence """ dp = [0] * len(nums) L = 0 for i, x in enumerate(nums): j = bl(dp, x, lo=0, hi=max(L, 0)) if j == L: L += 1 dp[j] = x return L
def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ dp = [0] * len(nums) L = 0 for i, x in enumerate(nums): j = bl(dp, x, lo=0, hi=max(L, 0)) if j == L: L += 1 dp[j] = x return L
def activityNotifications(expenditure, d): notifyCount = 0 trailing_expenditure = sorted(expenditure[0:d]) mid_index = d // 2 for i in range(d, n): day_expenditure = expenditure[i] if (day_expenditure >= 2 * median(trailing_expenditure, mid_index, d)): notifyCount += 1 del trailing_expenditure[bl(trailing_expenditure, expenditure[i - d])] ir(trailing_expenditure, day_expenditure) return notifyCount
def solve(a, n): ans = 0 ab = [] ef = [] for i in range(n): for j in range(n): for k in range(n): ab.append(a[i]*a[j]+a[k]) if a[k] != 0: ef.append((a[i]+a[j])*a[k]) # print(ab) # print(ef) ab.sort() ef.sort() i = 0 while i < n**3: lo = bl(ab, ab[i]) hi = br(ab, ab[i]) ans += (hi-lo)*(br(ef, ab[i])-bl(ef, ab[i])) i = hi return ans
def main(): read = stdin.readline l, n, q = map(int, read().split()) s = list(map(int, read().split())) d = bytes(map(int, read().split())) for i in range(n): s[i] -= 1 l -= 1 left = [] right = [] for i in range(n): if d[i]: right.append(s[i]) right.append(-2 * l + s[i]) right.append(2 * l + s[i]) else: right.append(-s[i]) right.append(-2 * l - s[i]) right.append(2 * l - s[i]) right.sort() #; left.sort () for i in range(len(right) - 1, -1, -1): left.append(-right[i]) setleft = set(left) for q_ in range(q): t, p = map(int, read().split()) t %= 2 * l t_sl = t in setleft tm = bl(left, 1 + t) + bl(right, 1 - t) lo = -1 hi = l while lo < hi: mid = (lo + hi) // 2 if br(left, mid + t) + br(right, mid - t) - tm + t_sl >= p: hi = mid else: lo = mid + 1 print(hi + 1)
def main(): from sys import stdin, stdout from bisect import bisect_left as bl r, w = raw_input, stdout.write n = int(r()) arr = map(int, r().split()) diffArr = [abs(arr[i] - arr[i - 1]) for i in xrange(1, n)] qs = int(r()) # Log preprocess log = [0] * (n + 1) for i in xrange(2, n + 1): log[i] = log[i // 2] + 1 # Shift preprocess pow = [1 << i for i in xrange(log[n] + 1)] # build sparse table k = log[n] + 1 sTable = [[0] * (n + 1) for i in xrange(k)] for i in xrange(len(diffArr)): sTable[0][i] = diffArr[i] for j in xrange(1, k + 1): for i in xrange(n + 1): if i + (1 << j) > n: break sTable[j][i] = max(sTable[j - 1][i], sTable[j - 1][i + pow[j - 1]]) def query(l, r): j = log[r - l + 1] return maxx(sTable[j][l], sTable[j][r - pow[j] + 1]) maxx = max for i in xrange(qs): t, d = map(int, r().split()) idx = bl(arr, t) idx = idx if idx < n and arr[idx] == t else idx - 1 ans, L, R = idx, 0, idx - 1, while L <= R: m = (L + R) >> 1 j = log[R - m + 1] if maxx(sTable[j][m], sTable[j][R - pow[j] + 1]) <= d: R = m - 1 ans = m else: L = m + 1 w('%i\n' % (ans + 1))
def solve(c, k): for i in range(1, len(c)): c[i] += c[i-1] res = 0 for i in range(len(c)): l = bl(c, c[i]+k, lo=i+1) r = br(c, c[i]+k) if c[i] == k: res += 1 if l != r: res += r - l print(res)
def removeRange(self, left, right): """ :type left: int :type right: int :rtype: void """ l, r = bl(self._X, left), br(self._X, right) self._X[l:r] = [left] * (l % 2 == 1) + [right] * (r % 2 == 1) # Your RangeModule object will be instantiated and called as such: # obj = RangeModule() # obj.addRange(left,right) # param_2 = obj.queryRange(left,right) # obj.removeRange(left,right)
def addRange(self, left, right): """ :type left: int :type right: int :rtype: void """ ivs = self.ivs ilo, ihi = bl(ivs, left), br(ivs, right) if ilo%2 == 1: ilo -= 1 left = ivs[ilo] if ihi%2 == 1: right = ivs[ihi] ihi += 1 self.ivs = ivs[:ilo] + [left, right] + ivs[ihi:]
def solution(pN): s = "" while 1: cnt1, cnt2 = 0, 0 l, u = map(int, input().split()) if l == u == -1: break ans = pN[bl(pN, l) : br(pN, u)] cnt1 = len(ans) for i in ans: if i % 4 == 1: cnt2 += 1 if l <= 2 and u >= 2: cnt2 += 1 # print(l, u, cnt1, cnt2) s += str(l) + " " + str(u) + " " + str(cnt1) + " " + str(cnt2) + "\n"
def removeRange(self, left, right): """ :type left: int :type right: int :rtype: void """ ivs = self.ivs ilo, ihi = bl(ivs, left), br(ivs, right) new = [] if ilo%2 == 1: ilo -= 1 new += [ivs[ilo], left] if ihi%2 == 1: new += [right, ivs[ihi]] ihi += 1 self.ivs = ivs[:ilo] + new + ivs[ihi:]
def main(): read = stdin.readline ql = [] q = int(read()) rmax = 0 for q_ in range(q): l, r = map(int, read().split()) if r > rmax: rmax = r ql.append((l, r)) trian = [1] maxrt = min(int((rmax * 2)**.5 + 2), 1414215) for i in range(2, maxrt): trian.append(trian[-1] + i) #print (trian) for l, r in ql: uix = br(trian, r) """lo = 0; rct = uix while lo < rct: md = (lo + rct) // 2 if trian [0] + trian [md] > r: rct = md else: lo = md + 1 lo = 0; lct = uix while lo < lct: md = (lo + lct) // 2 if trian [0] + trian [md] >= l: lct = md else: lo = md + 1""" rct = br(trian, r - 1) lct = bl(trian, l - 1) ct = rct - lct #print (rct, lct, ct) for i in range(1, uix): if trian[i] * 2 > r: break while rct > i and trian[i] + trian[rct] > r: rct -= 1 #rct = br (trian, r - trian [i]) if lct > i: #lct = bl (trian, l - trian [i]) while lct > i and trian[i] + trian[lct - 1] >= l: lct -= 1 else: lct = i #if i > 809240: print (rct, lct, l, r, uix) ct += rct - lct + 1 print(ct)
def main(): read = stdin.readline n = int(read()) d = dict() i = 1 while i <= n: s = read().rstrip() if s in d: d[s].append(i) else: d[s] = [i] i += 1 q = int(read()) while q: l, r, s = read().split() ans = 0 if s in d: ans = (br(d[s], int(r)) - bl(d[s], int(l))) print(ans) q -= 1
def book(self, start, end): """ :type start: int :type end: int :rtype: int """ from bisect import bisect_left as bl, bisect_right as br, insort_left as il from heapq import heappop, heappush i, j = bl(self.es, start), br(self.ss, end) il(self.ss, start, i, j) il(self.es, end, i, j) heap = [] for pp in range(i, j + 1): while heap and heap[0] <= self.ss[pp]: heappop(heap) heappush(heap, self.es[pp]) self.k = max(self.k, len(heap)) return self.k
def main(): read = stdin.readline n, q = map(int, read().split()) a = list(map(int, read().split())) maxval = 20001 di = [[] for i in range(maxval)] V = [[] for i in range(maxval)] for i in range(1, maxval): for j in range(i, maxval, i): di[j].append(i) for i in range(n): for j in range(len(di[a[i]])): V[di[a[i]][j]].append(i) from bisect import bisect_left as bl for q_ in range(q): i, x = map(int, read().split()) i -= 1 print(len(V[x]) - bl(V[x], i))
def main(): read = stdin.readline write = stdout.write n, s = map(int, read().split()) t = [0] * n d = [0] * n for i in range(n): t[i], d[i] = map(int, read().split()) download = [0] for i in range(1, n): download += (download[-1] + (t[i] - t[i - 1]) * d[i - 1]), download += s if s > download[-1] else download[-1], nom, den = 0, 1 if d[-1] > 0: nom, den = s, d[-1] j = -1 i = bl(download, s) if not i: i = 1 while i < n: while download[i] - download[j + 1] >= s: j += 1 a = s - (download[i - 1] - download[j]) if a >= 0: b = d[i - 1] a += b * (t[i - 1] - t[j]) if a * den < b * nom: nom, den = a, b a = s - (download[i] - download[j + 1]) if a >= 0: b = d[j] a += b * (t[i] - t[j + 1]) if a * den < b * nom: nom, den = a, b i += 1 b = d[-1] while j < n: a = s - (download[-2] - download[j]) if a >= 0: a += b * (t[-1] - t[j]) if a * den < b * nom: nom, den = a, b j += 1 gcd_ = gcd(nom, den) if gcd_ != 1: nom //= gcd_ den //= gcd_ write(str(nom) + "/" + str(den) + "\n")
def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ print nums,": ", if len(nums) == 0: return [] if len(nums) == 1: return [0] res=[] ans=[] for v in nums[::-1]: if not res: res.append(v) ans.append(0) continue idx = bl(res, v) res[idx:idx] = [v] ans.append(idx) return ans[::-1]
def lcs4(): N = int(sys.stdin.readline()) A = list(map(int, sys.stdin.readline().split())) B = list(map(int, sys.stdin.readline().split())) tmp = [0 for _ in range(N + 1)] for i in range(N): tmp[B[i]] = i A = [tmp[A[i]] for i in range(N)] lis = [-float('inf')] for num in A: if lis[-1] < num: lis.append(num) else: lis[bl(lis, num)] = num print(len(lis) - 1)
def sortedSquares(self, A: List[int]) -> List[int]: start = bl(A, 0) l, r = start - 1, start res = [] while l >= 0 and r < len(A): if abs(A[l]) <= abs(A[r]): res.append(A[l]*A[l]) l -= 1 else: res.append(A[r]*A[r]) r += 1 while r < len(A): res.append(A[r]*A[r]) r += 1 while l >= 0: res.append(A[l]*A[l]) l -= 1 return res
def locateinlist(lst,value,bias='closest'): """ Finds index in a sorted list of the value closest to a given value If two numbers are equally close, return the smallest number. based on http://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value lst: list list of values to search value: float or int value number to find bias: 'lesser','greater', or 'closest' default 'left' 'lesser' will return the position of the value just less than the provided value 'greater' will return the position of the value just greater than the provided value 'closest' will return the index of the nearest value to the one provided """ from bisect import bisect_left as bl pos = bl(lst, value) if pos == 0: # if at start of list return pos elif pos == len(lst): # if insertion is beyond index range return pos -1 if lst[pos] == value: # if an exact match is found return pos if bias == 'greater': # return value greater than the value (bisect_left has an inherent bias to the right) return pos if bias == 'lesser': # return value lesser than the provided return pos -1 if bias == 'closest': # check differences between index and index-1 and actual value, return closest adjval = abs(lst[pos-1] - value) curval = abs(lst[pos] - value) if adjval < curval: # if the lesser value is closer return pos-1 if adjval == curval: # if values are equidistant return pos-1 else: return pos
def trimspectrum(x,y,left,right): """trims a spectrum to the left and right bounds""" l,r = bl(x,left),br(x,right) # find indicies return x[l:r],y[l:r] # trim spectrum
def plotms(realspec,simdict={},**kwargs): """ plots a formatted mass spectrum and optionally overlays predicted isotope patterns realspec: the spectrum to plot list of [[mzvalues],[intvalues]] simdict: molecular formulae to predict and overlay can be handed several options - a dictionary of formulas (with each formula being its own dictionary with colour and alpha keys) - a list of formulas (all overlays will default to black with 0.5 alpha) - a single formula (black with 0.5 alpha) kwargs: many parameters can be changed to tweak the appearance of the plot see the settings dictionary in this function for details """ def localmax(x,y,xval,lookwithin=1): """finds the local maximum within +/- lookwithin of the xval""" l,r = bl(x,xval-lookwithin),br(x,xval+lookwithin) try: return max(y[l:r]) except ValueError: raise ValueError("No maximum value found in range, perhaps wrong window region?") def trimspectrum(x,y,left,right): """trims a spectrum to the left and right bounds""" l,r = bl(x,left),br(x,right) # find indicies return x[l:r],y[l:r] # trim spectrum def estimatedem(x,y,em,simmin,simmax,lookwithin=1): """estimates the exact mass of a peak""" l,r = bl(x,simmin-lookwithin),br(x,simmax+lookwithin) # narrow range to that of the isotope pattern locmax = max(y[l:r]) # find local max in that range for ind,val in enumerate(y): if val == locmax: # if the y-value equals the local max if ind >= l and ind <= r: # and if the index is in the range (avoids false locations) return x[ind] difleft = abs(em-simmin) difright = abs(em-simmax) return '>%.1f' %max(difleft,difright) # if no match is found, return maximum difference def checksimdict(dct): """ checks the type of simdict, converting to dictionary if necessary also checks for alpha and colour keys and adds them if necessary (defaulting to key @ 0.5) """ if type(dct) is not dict: if type(dct) is str: dct = {dct:{}} elif type(dct) is list or type(dct) is tuple: tdct = {} for i in dct: tdct[i] = {} dct = tdct for species in dct: if dct[species].has_key('colour') is False: dct[species]['colour'] = 'k' if dct[species].has_key('alpha') is False: dct[species]['alpha'] = 0.5 return dct import sys from _classes._Colour import Colour from _classes._Molecule import Molecule from tome_v02 import autoresolution,normalize import pylab as pl from bisect import bisect_left as bl from bisect import bisect_right as br settings = { # default settings 'mz':'auto', # m/z bounds for the output spectrum 'outname':'spectrum', # name for the output file 'output':'save', # 'save' or 'show' the figure 'simtype':'bar', # simulation overlay type ('bar' or 'gaussian') 'spectype':'continuum', # spectrum type ('continuum' or 'centroid') 'maxy':'max', # max or value 'norm':True, # True or False 'simnorm':'spec', # top, spec, or value 'xlabel':True, # show x label 'ylabel':True, # show y label 'xvalues':True, #show x values 'yvalues':True, # show y values 'showx':True, # show x axis 'showy':True, # how y axis 'offsetx':True, # offset x axis (shows low intensity species better) 'fs':16, # font size 'lw':1.5, # line width for the plotted spectrum 'axwidth':1.5, # axis width 'simlabels':False, # show labels isotope for patterns 'bw':'auto', # bar width for isotope patterns (auto does 2*fwhm) 'specfont':'Arial', # the font for text in the plot 'size':[7.87,4.87], # size in inches for the figure 'dpiout':300, # dpi for the output figure 'exten':'png', # extension for the output figure 'res':False, # output the resolution of the spectrum 'delta':False, # output the mass delta between the spectrum and the isotope patterns 'stats':False, # output the goodness of match between the spectrum and the predicted isotope patterns, 'speccolour':'k', # colour for the spectrum to be plotted 'padding':'auto', # padding for the output plot 'verbose':True, # verbose setting 'normwindow':'fwhm', # the width of the window to look for a maximal value around the expected exact mass for a peak 'annotations':None, # annotations for the spectrum in dictionary form {'thing to print':[x,y],} 'normrel':100., # the maximum value for normalization } if set(kwargs.keys()) - set(settings.keys()): # check for invalid keyword arguments string = '' for i in set(kwargs.keys()) - set(settings.keys()): string += ` i` raise KeyError('Unsupported keyword argument(s): %s' %string) settings.update(kwargs) # update settings from keyword arguments res = autoresolution(realspec[0],realspec[1]) # calculate resolution simdict = checksimdict(simdict) # checks the simulation dictionary for species in simdict: # generate Molecule object and set x and y lists simdict[species]['colour'] = Colour(simdict[species]['colour']) simdict[species]['mol'] = Molecule(species, res=res) if settings['simtype'] == 'bar': simdict[species]['x'],simdict[species]['y'] = simdict[species]['mol'].barip if settings['simtype'] == 'gaussian': simdict[species]['mol'].gaussianisotopepattern() simdict[species]['x'],simdict[species]['y'] = simdict[species]['mol'].gausip if settings['mz'] == 'auto': # automatically determine m/z range if settings['verbose'] is True: sys.stdout.write('Automatically determining m/z window') mz = [10000000,0] for species in simdict: simdict[species]['bounds'] = simdict[species]['mol'].bounds() # calculate bounds if simdict[species]['bounds'][0] < mz[0]: mz[0] = simdict[species]['bounds'][0]-1 if simdict[species]['bounds'][1] > mz[1]: mz[1] = simdict[species]['bounds'][1]+1 if mz == [10000000,0]: mz = [min(realspec[0]),max(realspec[0])] settings['mz'] = mz if settings['verbose'] is True: sys.stdout.write(': %i - %i\n' %(int(mz[0]),int(mz[1]))) sys.stdout.flush() else: mz = settings['mz'] realspec[0],realspec[1] = trimspectrum(realspec[0],realspec[1],settings['mz'][0]-1,settings['mz'][1]+1) # trim real spectrum for efficiency if settings['norm'] is True: # normalize spectrum realspec[1] = normalize(realspec[1],settings['normrel']) for species in simdict: # normalize simulations if settings['simnorm'] == 'spec': # normalize to maximum around exact mass if settings['normwindow'] == 'fwhm': # if default, look within the full width at half max window = simdict[species]['mol'].fwhm else: # otherwise look within the specified value window = settings['normwindow'] simdict[species]['y'] = normalize(simdict[species]['y'],localmax(realspec[0],realspec[1],simdict[species]['mol'].em,window)) elif settings['simnorm'] == 'top': # normalize to top of the y value if settings['maxy'] == 'max': raise ValueError('Simulations con only be normalized to the top of the spectrum when the maxy setting is a specific value') simdict[species]['y'] = normalize(simdict[species]['y'],settings['maxy']) elif type(settings['simnorm']) is int or type(settings['simnorm']) is float: # normalize to specified value simdict[species]['y'] = normalize(simdict[species]['y'],settings['simnorm']) if settings['delta'] is True: est = estimatedem(realspec[0],realspec[1],simdict[species]['mol'].em,min(simdict[species]['x']),max(simdict[species]['x'])) # try to calculate exact mass if type(est) is float: simdict[species]['delta'] = simdict[species]['mol'].em - est else: simdict[species]['delta'] = est pl.clf() # clear and close figure if open pl.close() fig = pl.figure(figsize = tuple(settings['size'])) ax = fig.add_subplot(111) ax.spines["right"].set_visible(False) #hide right and top spines ax.spines["top"].set_visible(False) if settings['showx'] is False: ax.spines["bottom"].set_visible(False) # hide bottom axis if settings['showy'] is False: ax.spines["left"].set_visible(False) # hide left axis for axis in ["top","bottom","left","right"]: ax.spines[axis].set_linewidth(settings['axwidth']) if settings['offsetx'] is True: # offset x axis ax.spines["bottom"].set_position(('axes',-0.01)) font = {'fontname':settings['specfont'],'fontsize':settings['fs']} #font parameters for axis/text labels tickfont = pl.matplotlib.font_manager.FontProperties(family=settings['specfont'],size=settings['fs']) # font parameters for axis ticks ax.set_xlim(settings['mz']) # set x bounds if settings['maxy'] == 'max': # set y bounds ax.set_ylim((0,max(realspec[1]))) top = max(realspec[1]) elif type(settings['maxy']) is int or type(settings['maxy']) is float: ax.set_ylim((0,settings['maxy'])) top = settings['maxy'] if settings['simtype'] == 'bar': # generates zeros for bottom of bars (assumes m/z spacing is equal between patterns) for species in simdict: simdict[species]['zero'] = [] for i in simdict[species]['x']: simdict[species]['zero'].append(0.) for species in simdict: # for each species for subsp in simdict: # look at all the species if subsp != species: # if it is not itself ins = bl(simdict[subsp]['x'],simdict[species]['x'][-1]) # look for insertion point if ins > 0 and ins < len(simdict[subsp]['x']): # if species highest m/z is inside subsp list for i in range(ins): # add intensity of species to subsp zeros # used -ins+i-1 to fix an error, with any luck this won't break it next time simdict[subsp]['zero'][i] += simdict[species]['y'][-ins+i-1] if settings['res'] is True and settings['spectype'] != 'centroid': #include resolution if specified (and spectrum is not centroid) ax.text(mz[1],top*0.95,'resolution: '+str(round(res))[:-2],horizontalalignment='right',**font) for species in simdict: # plot and label bars if settings['simtype'] == 'bar': if settings['bw'] == 'auto': bw = simdict[species]['mol'].fwhm*2 else: bw = settings['bw'] ax.bar(simdict[species]['x'], simdict[species]['y'], bw, alpha = simdict[species]['alpha'], color = simdict[species]['colour'].mpl, linewidth=0, align='center',bottom=simdict[species]['zero']) elif settings['simtype'] == 'gaussian': ax.plot(simdict[species]['x'], simdict[species]['y'], alpha = simdict[species]['alpha'], color = simdict[species]['colour'].mpl, linewidth=settings['lw']) ax.fill(simdict[species]['x'], simdict[species]['y'], alpha = simdict[species]['alpha'], color = simdict[species]['colour'].mpl, linewidth=0) if settings['simlabels'] is True or settings['stats'] is True or settings['delta'] is True: # if any labels are to be shown string = '' bpi = simdict[species]['y'].index(max(simdict[species]['y'])) # index of base peak if settings['simlabels'] is True: # species name string += species if settings['stats'] is True or settings['delta'] is True: # add return if SER or delta is called for string += '\n' if settings['stats'] is True: # standard error of regression string += 'SER: %.2f\n' %simdict[species]['mol'].compare(realspec) if settings['delta'] is True: # mass delta string += 'mass delta: ' if type(simdict[species]['delta']) is float: string += '%.3f' %simdict[species]['delta'] else: string += '%s' %simdict[species]['delta'] ax.text(simdict[species]['x'][bpi],top*(1.01),string, color = simdict[species]['colour'].mpl, horizontalalignment='center', **font) if settings['spectype'] == 'continuum': ax.plot(realspec[0], realspec[1], linewidth=settings['lw'], color=Colour(settings['speccolour']).mpl) elif settings['spectype'] == 'centroid': dist = [] for ind,val in enumerate(realspec[0]): # find distance between all adjacent m/z values if ind == 0: continue dist.append(realspec[0][ind]-realspec[0][ind-1]) dist = sum(dist)/len(dist) # average distance ax.bar(realspec[0], realspec[1], dist*0.75, linewidth=0, color=Colour(settings['speccolour']).mpl, align='center', alpha=0.8) if settings['annotations'] is not None: for label in settings['annotations']: ax.text( settings['annotations'][label][0], settings['annotations'][label][1], label, horizontalalignment='center', **font ) # show or hide axis values/labels as specified if settings['yvalues'] is False: # y tick marks and values ax.tick_params(axis='y', labelleft='off',length=0) if settings['yvalues'] is True: # y value labels ax.tick_params(axis='y', length=settings['axwidth']*3, width=settings['axwidth'], direction='out',right='off') for label in ax.get_yticklabels(): label.set_fontproperties(tickfont) if settings['ylabel'] is True: # y unit if settings['norm']: # normalized ax.set_ylabel('relative intensity', **font) else: # set to counts ax.set_ylabel('intensity (counts)', **font) if settings['xvalues'] is False: # x tick marks and values ax.tick_params(axis='x', labelbottom='off',length=0) if settings['xvalues'] is True: # x value labels ax.tick_params(axis='x', length=settings['axwidth']*3, width=settings['axwidth'] ,direction='out',top = 'off') for label in ax.get_xticklabels(): label.set_fontproperties(tickfont) if settings['xlabel'] is True: # x unit ax.set_xlabel('m/z', style='italic', **font) if settings['padding'] == 'auto': pl.tight_layout(pad=0.5) # adjust subplots if settings['simlabels'] is True or settings['stats'] is True or settings['delta'] is True: pl.subplots_adjust(top = 0.90) # lower top if details are called for elif type(settings['padding']) is list and len(settings['padding']) == 4: pl.subplots_adjust(left=settings['padding'][0], right=settings['padding'][1], bottom=settings['padding'][2], top=settings['padding'][3]) if settings['output'] == 'save': # save figure outname = '' # generate tag for filenaming for species in simdict: outname+=' '+species outname = settings['outname'] + outname + '.' + settings['exten'] pl.savefig(outname, dpi=settings['dpiout'], format=settings['exten'], transparent=True) if settings['verbose'] is True: sys.stdout.write('Saved figure as:\n"%s"\nin the working directory' %outname) elif settings['output'] == 'show': # show figure pl.show()
# 474B: Worms # Start Time: 4:32 p.m. 5-1-15 # End Time: 4:54 a.m. 5-1-15 runtime error dunno why from bisect import bisect_left as bl if __name__ == "__main__": v = [0 for _ in range(10**5 + 1)] n = int(input()) c = list(map(int, input().split())) for i in range(1, n): c[i] += c[i-1] s = 0 for idx, val in enumerate(c): for _ in range(val): v[s] = idx + 1 s += 1 q = int(input()) t = list(map(int, input().split())) for val in t: print(bl(c, val-1) + 1)
from bisect import bisect_left as bl, bisect_right as br n, k = map(int, raw_input().split());a=sorted(map(int, raw_input().split())) print sum([br(a,a[i]+k)-bl(a,a[i]+k) for i in xrange(n)])