def split(self): """ Try to breakup the chebfun """ while self.naf: edges = self.edges edge_genuine = [True for x in edges] for i,fun in enumerate(self.funcs): a,b = self.edges[i:i+1] c = tools.detectedge(a,b,fun) if c - a > 1e-14*(b-a) and b-c > 1e-14*(b-a): #genuine edge ind = bisect.bisect(edges,c) edges.insert(ind,c) edge_genuine.insert(ind,True) elif c-a < 1e-14*(b-a): c = 0.01*(b-a) + a ind = bisect.bisect(edges,c) edges.insert(ind,c) edge_genuine.insert(ind,False) elif b-c < 1e-14*(b-a): c = b - 0.01*(b-a) ind = bisect.bisect(edges,c) edges.insert(ind,c) edge_genuine.insert(ind,False) else: c = (a+b)/2. ind = bisect.bisect(edges,c) edges.insert(ind,c) edge_genuine.insert(ind,False)
def searchMatrix2(matrix, target): ''' subtract 1 as the bisect call "returns an insertion point which comes after (to the right of) any existing entries of x in a." ''' if not matrix or not matrix[0]: return False i = bisect.bisect([row[0] for row in matrix], target) - 1 j = bisect.bisect(matrix[i], target) - 1 return matrix[i][j] == target
def find_historic_trends(currency_pair, before_prices): prices, times, volumes = load_time_series(currency_pair, None, None) trends = [] for index in range(80 * 24, len(prices)): trends.append( abs( np.mean([ prices[index] - prices[index - back_step] for back_step in range(24, 80 * 24, 24) ]))) trends = sorted(trends) delta = abs( np.mean([ before_prices[-1] - before_prices[-back_step] for back_step in range(2, 80) ])) index = bisect.bisect(trends, delta) percentile = int((float(index) / len(trends)) * 100) return percentile
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: result = [] # return merged or empty if no overlap overlap = lambda x, y: max(x[0], y[0]) <= min(x[1], y[1]) # O(1) merge = lambda x, y: [min(x[0], y[0]), max(x[1], y[1])] # O(1) merge_id = [] for i, interval in enumerate(intervals): # O(N) if overlap(interval, newInterval) > 0: merge_id.append(i) if not merge_id: intervals.insert(bisect.bisect(intervals, newInterval), newInterval) # O(log(N)) return intervals mini = merge_id[0] # insert place for _ in range(len(merge_id)): # O(N) newInterval = merge(newInterval, intervals.pop(mini)) intervals.insert(mini, newInterval) return intervals
def at(l): from bisect import bisect jobs = sorted(zip(l[0], l[1], l[2]), key=lambda v: v[1]) dp = [[0, 0]] for s, e, p in jobs: i = bisect.bisect(dp, [s + 1, 0]) - 1 if dp[i][1] + p > dp[-1][1]: dp.append([e, dp[i][1] + p]) print(dp[-1][1])
def firstBadVersion(self, n): """ :type n: int :rtype: int """ class Wrap: def __getitem__(self, i): return isBadVersion(i) return bisect.bisect(Wrap(), False, 0, n)
def get_price_trends(currency_pair, global_ranking): before_prices, times = get_time_series(currency_pair, 800, "D") if currency_pair[4:7] == "JPY": pip_size = 0.01 else: pip_size = 0.0001 trend_map = {} for index in range(1, len(before_prices)): for time_index in [1, 2, 3, 4, 5, 10, 15, 20, 40, 60, 80]: if time_index not in trend_map: trend_map[time_index] = [] if index + time_index < len(before_prices): trend_map[time_index].append( abs((before_prices[-index] - before_prices[-time_index - 1 - index]) / pip_size)) for time_index in [1, 2, 3, 4, 5, 10, 15, 20, 40, 60, 80]: trend_map[time_index] = sorted(trend_map[time_index]) table_str, final_decision = generate_price_movement_table( trend_map, before_prices, currency_pair, global_ranking) delta_map = {} percentile_map = {} for time_index in [1, 2, 3, 4, 5, 10, 15, 20, 40, 60, 80]: delta_map[time_index] = (before_prices[-1] - before_prices[-time_index - 1]) / pip_size index = bisect.bisect(trend_map[time_index], abs(delta_map[time_index])) percentile_map[time_index] = int( (float(index) / len(trend_map[time_index])) * 100) return delta_map, percentile_map, table_str, final_decision
def generate_price_movement_table(trend_map, before_prices, currency_pair, global_ranking): if currency_pair[4:7] == "JPY": pip_size = 0.01 else: pip_size = 0.0001 trend_indicator = find_historic_trends(currency_pair, before_prices) is_trend = trend_indicator > 50 if is_trend: table_str = "<table border=1 width=75%><tr><th colspan=12><center>Recommend <b>Trend Following</b> Strategy</center></th></tr>" else: table_str = "<table border=1 width=75%><tr><th colspan=12><center>Recommend <b>Trend Reversal</b> Strategy</center></th></tr>" table_str += "<tr><th>Time Frame</th><th>BUY / SELL</th><th>Price Delta (%)</th><th colspan=3><font color='red'>High Risk</font></th><th colspan=3><font color='orange'>Medium Risk</font></th><th colspan=3><font color='green'>Low Risk</font></th></tr>" table_str += "<tr><th colspan=3></th><th>TP Pips</th><th>SL Pips</th><th>Amount</th><th>TP Pips</th><th>SL Pips</th><th>Amount</th><th>TP Pips</th><th>SL Pips</th><th>Amount</th></tr>" final_decision = {} final_decision["is_trend"] = is_trend final_decision["trend_indicator"] = trend_indicator is_trend = False buy_percentiles = [] sell_percentiles = [] sell_indexes = [] buy_indexes = [] time_frames = [ '1 Day', '2 Days', '3 Days', '4 Days', '1 Week', '2 Weeks', '3 Weeks', '1 Month', '2 Months', '3 Months', '4 Months', 'Average' ] for time_index, time_frame in zip( [1, 2, 3, 4, 5, 10, 15, 20, 40, 60, 80, 0], time_frames): if time_index == 0: if len(buy_percentiles) > len(sell_percentiles): percentile = int(np.mean(buy_percentiles)) time_indexes = buy_indexes else: percentile = int(np.mean(sell_percentiles)) time_indexes = sell_indexes if is_trend: delta = 1 if len(buy_percentiles) > len( sell_percentiles) else -1 else: delta = 1 if len(buy_percentiles) < len( sell_percentiles) else -1 if delta < 0: final_decision["percentile"] = -percentile else: final_decision["percentile"] = percentile else: delta = (before_prices[-1] - before_prices[-time_index - 1]) / pip_size index = bisect.bisect(trend_map[time_index], abs(delta)) percentile = int((float(index) / len(trend_map[time_index])) * 100) if time_index != 0: table_str += "<tr><td>{}</td>".format(time_frame) else: table_str += "<tr><td><b>{}</b></td>".format(time_frame) global_ranking.append({ "time_frame": time_frame, "percentile": percentile, "dir": delta > 0, "pair": currency_pair }) if is_trend: if delta < 0: is_buy = False table_str += "<td><font color='red'>SELL</font></td>" table_str += "<td><font color='red'>{}%</font></td>".format( percentile) else: is_buy = True table_str += "<td><font color='green'>BUY</font></td>" table_str += "<td><font color='green'>{}%</font></td>".format( percentile) else: if delta < 0: is_buy = True table_str += "<td><font color='green'>BUY</font></td>" table_str += "<td><font color='red'>{}%</font></td>".format( percentile) else: is_buy = False table_str += "<td><font color='red'>SELL</font></td>" table_str += "<td><font color='green'>{}%</font></td>".format( percentile) if time_index != 0: if is_buy: buy_percentiles.append(percentile) buy_indexes.append(time_index) else: sell_percentiles.append(percentile) sell_indexes.append(time_index) else: final_decision["is_buy"] = is_buy for sl in [50, 75, 95]: if time_index == 0: trends = [trend_map[index] for index in time_indexes] trends = [item for sublist in trends for item in sublist] range_val = int(np.percentile(trends, sl) - abs(delta)) delta = np.mean(trends) final_decision["TP"] = int(abs(delta)) final_decision["SL"] = range_val else: range_val = int( np.percentile(trend_map[time_index], sl) - abs(delta)) if range_val <= 0: table_str += "<td colspan=3></td>" continue if (delta < 0) == is_trend: table_str += "<td><font color='red'>{}</font></td>".format( int(abs(delta))) table_str += "<td><font color='green'>{}</font></td>".format( range_val) else: table_str += "<td><font color='green'>{}</font></td>".format( int(abs(delta))) table_str += "<td><font color='red'>{}</font></td>".format( range_val) amount = int(round(100 * (float(percentile) / range_val))) table_str += "<td class='pip_diff'>{}</td>".format(amount) if time_index == 0 and sl == 95: final_decision["amount"] = amount table_str += "</tr>" table_str += "</table>" return table_str, final_decision
def searchMatrix3(matrix, target): return len(matrix) > 0 and len(matrix[0]) > 0 and matrix[ bisect.bisect([row[0] for row in matrix], target) - 1][bisect.bisect( matrix[bisect.bisect([row[0] for row in matrix], target) - 1], target) - 1] == target
def nextGreatestLetter2(letters, target): import bisect.bisect index = bisect.bisect(letters, target) return (letters[index % len(letters)])
def getBisect(self, key, timestamp): A = self.M.get(key, None) if A is None: return "" i = bisect.bisect(A, (timestamp, chr(127))) return A[i - 1][1] if i else ""
def get(self, index: int, snap_id: int) -> int: i = bisect.bisect(self.A[index], [snap_id+1]) - 1 return self.A[index][i][1]
def get(self, index, snap_id): i = bisect.bisect(self.A[index], [snap_id + 1]) - 1 return self.A[index][i][1]
self.snap_id = 0 def set(self, index, val): self.A[index].append([self.snap_id, val]) def snap(self): self.snap_id += 1 return self.snap_id - 1 def get(self, index, snap_id): i = bisect.bisect(self.A[index], [snap_id + 1]) - 1 return self.A[index][i][1] import bisect a = [[1,100], [2,200], [3,300]] bisect.bisect(a, [2]) => 1 bisect.bisect(a, [2,200]) => 2 #自己重寫, time complexity set O(1), get O(logn), space complexity O(n) import bisect class SnapshotArray: def __init__(self, length: int): self.A = [[[-1, 0]] for _ in range(length)] self.snap_id = 0 def set(self, index: int, val: int) -> None: self.A[index].append([self.snap_id, val])
print(index(a, 3)) # 3. Write a Python program to insert items into a list in sorted order. # Expected Output: # Original List: # [25, 45, 36, 47, 69, 48, 68, 78, 14, 36] # Sorted List: # [14, 25, 36, 36, 45, 47, 48, 68, 69, 78] import bisect # Sample list my_list = [25, 45, 36, 47, 69, 48, 68, 78, 14, 36] print("Original List:") print(my_list) sorted_list = [] for i in my_list: position = bisect.bisect(sorted_list, i) bisect.insort(sorted_list, i) print("Sorted List:") print(sorted_list) # 4. Write a Python program to find the first occurrence of a given number in a sorted list using Binary Search(bisect). # Expected Output: # First occurrence of 8 is present at index 4 from bisect import bisect_left def Binary_Search(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else:
breakpoints = [30, 44, 66, 75, 85] def grade(total): return grades[bisect(breakpoints, total)] grade_map = map(grade, [33, 99, 77, 44, 12, 88]) grade_map list(grade_map) #%% import bisect import random random.seed(3) l = [] for i in range(10): r = random.randint(1, 50) pos = bisect.bisect_left(l, r) bisect.insort_left(l, r) print('%2d %2d' % (r, pos), l) #%% import bisect import random random.seed(3) l = [] for i in range(10): r = random.randint(1, 50) pos = bisect.bisect(l, r) bisect.insort(l, r) print('%2d %2d' % (r, pos), l)