def put_event(self, event): """ Insert events into self.map and prune oldest events if they exceed the size limit. Args: event: dict event to be tracked. Its integrity is validated by validate_input Returns: """ try: current_timestamp_in_sec = int( datetime.now(tz=timezone.utc).timestamp()) if not self.queue: self.queue.append(current_timestamp_in_sec) elif current_timestamp_in_sec not in self.queue: if current_timestamp_in_sec > self.queue[-1]: self.queue.append(current_timestamp_in_sec) else: # Handle the case when timestamp is out of sync bisect.insort(self.queue, current_timestamp_in_sec) self.map[current_timestamp_in_sec] += 1 if len(self.queue) > self.maxsize: expired = self.queue.popleft() del self.map[expired] return { "error_code": SUCCESS["code"], "error_message": SUCCESS["message"] } except Exception: return { "error_code": INSERT_EVENT_FAILED["code"], "error_message": INSERT_EVENT_FAILED["message"] }
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: """ 思路: 1. 先计算二维前缀和presum 2. 固定上下界,列坐标从左至右扫描,找到presum[j+1][r]-presum[i][l]<=k的最大值,即presum[i][l] >= presum[j+1][r]-k的最大值 我们先将presum[j+1][r]-k有序插入arr中,每次遍历一个值后再arr中二分查找 @param matrix: @param k: @return: """ m, n = len(matrix), len(matrix[0]) presum = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m): for j in range(n): presum[i + 1][j + 1] = presum[i][j + 1] + presum[i + 1][j] + matrix[i][j] - presum[i][j] print(presum) res = float('-inf') # presum[i][r]-presum[i][l]<=k # 枚举上行 for i in range(m): # 枚举下行 for j in range(i, m): arr = [0] for r in range(n): t = presum[j + 1][r + 1] - presum[i][r + 1] index = bisect.bisect_left(arr, t - k) if index < len(arr): res = max(res, t - arr[index]) bisect.insort(arr, t) return res
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: dic = collections.defaultdict(list) m, n = len(mat), len(mat[0]) for i in range(m): for j in range(n): bisect.insort(dic[i - j], mat[i][j]) res = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): res[i][j] = dic[i - j].pop(0) return res
def mostVisitedPattern(self, u: List[str], t: List[int], w: List[str]) -> List[str]: n = len(u) dic = collections.defaultdict(list) for i in range(n): bisect.insort(dic[u[i]], (t[i], w[i])) name = collections.defaultdict(set) for k, v in dic.items(): for t in itertools.combinations([b for a, b in v], 3): name[t].add(k) return sorted(name.items(), key=lambda x: (-len(x[1]), x[0]))[0][0]
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: result = [] tmp = sorted(nums[:k]) result.append(tmp[-1]) for i in range(1, len(nums) - k + 1): tmp.pop(bisect.bisect_left(tmp, nums[i - 1])) bisect.insort(tmp, nums[i + k - 1]) result.append(tmp[-1]) return result
def rectangleArea(self, rectangles: List[List[int]]) -> int: def total_width_after_merge(itvls): sorted_intervals = sorted(itvls + [[float("inf"), float("inf")]]) s, e = sorted_intervals[0][0], sorted_intervals[0][1] res = [] for cs, ce in sorted_intervals[1:]: if cs > e: res.append([s, e]) s, e = cs, ce else: e = max(ce, e) return sum(e - s for s, e in res) total_area = 0 MOD = 10**9 + 7 y2x_itvls = defaultdict(deque) for x1, y1, x2, y2 in rectangles: if y1 != y2: bisect.insort(y2x_itvls[y1], (1, x1, x2)) bisect.insort(y2x_itvls[y2], (-1, x1, x2)) sorted_yvals = sorted(y2x_itvls.keys()) prev_y = sorted_yvals[0] active_itvls = [] for y in sorted_yvals: while y2x_itvls[y]: typ, xs, xe = y2x_itvls[y].popleft() height = y - prev_y total_area += (total_width_after_merge(active_itvls) * height) if typ == 1: active_itvls.append([xs, xe]) else: active_itvls.remove([xs, xe]) prev_y = y return total_area % MOD
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: result = [] def median(l): if len(l) % 2 == 1: return l[len(l) // 2] else: return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2 tmp = sorted(nums[:k]) result.append(median(tmp)) for i in range(1, len(nums) - k + 1): tmp.pop(bisect.bisect_left(tmp, nums[i - 1])) bisect.insort(tmp, nums[i + k - 1]) result.append(median(tmp)) return result
def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]: """ 思路:离线化,将查询数组和事物数组排序,降低时间复杂度(写了题解) @param rooms: @param queries: @return: """ # from sortedcontainers import SortedSet m, n = len(rooms), len(queries) # 将rooms和queries按照size从大到小排序 rooms.sort(key=lambda x: x[1], reverse=True) index = sorted(range(n), key=lambda i: queries[i][1], reverse=True) ids = [] j = 0 res = [-1] * n for i in index: preferred, minSize = queries[i] while j < m and rooms[j][1] >= minSize: bisect.insort(ids, rooms[j][0]) j += 1 if not ids: continue k = bisect.bisect_left(ids, preferred) if k == 0: res[i] = ids[0] elif k == len(ids): res[i] = ids[-1] else: if abs(ids[k] - preferred) < abs(ids[k - 1] - preferred): res[i] = ids[k] else: res[i] = ids[k - 1] return res
if root is None: return # If this is the last node of its level if (max_level[0] < level): print "%d " %(root.data), max_level[0] = level # Recur for right subtree first, then left subtree rightViewUtil(root.right, level+1, max_level) rightViewUtil(root.left, level+1, max_level) l = [] for _ in xrange(n): bisect.insort(l, input()) print '{:.1f}'.format(medium(l)) d = deque(seq[0:M]) Counter(d).most_common(1)[0][0] def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): i = bisect(breakpoints, score) return grades[i] [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] import random import bisect SIZE = 7 random.seed(1) my_list = [] for i in range(SIZE): new_item = random.randrange(SIZE * 2) bisect.insort(my_list, new_item) print('%2d ->' % new_item, my_list) l = [28, 14, '28', 5, '9', '1', 0, 6, '23', 19] import collections collections.UserDict() class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def get(self, key, default=None): try:
# 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: return -1
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)
def addNum(self, num: int) -> None: bisect.insort(self.arr, num)