codekingpro/portable-devtools
114k
1"""2Given a list of integers, made up of (hopefully) a small number of long runs3of consecutive integers, compute a representation of the form4((start1, end1), (start2, end2) ...). Then answer the question "was x present5in the original list?" in time O(log(# runs)).6"""7 8import bisect9from typing import List, Tuple10 11 12def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:13 """Represent a list of integers as a sequence of ranges:14 ((start_0, end_0), (start_1, end_1), ...), such that the original15 integers are exactly those x such that start_i <= x < end_i for some i.16 17 Ranges are encoded as single integers (start << 32 | end), not as tuples.18 """19 20 sorted_list = sorted(list_)21 ranges = []22 last_write = -123 for i in range(len(sorted_list)):24 if i + 1 < len(sorted_list) and sorted_list[i] == sorted_list[i + 1] - 1:25 continue26 current_range = sorted_list[last_write + 1 : i + 1]27 ranges.append(_encode_range(current_range[0], current_range[-1] + 1))28 last_write = i29 30 return tuple(ranges)31 32 33def _encode_range(start: int, end: int) -> int:34 return (start << 32) | end35 36 37def _decode_range(r: int) -> Tuple[int, int]:38 return (r >> 32), (r & ((1 << 32) - 1))39 40 41def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:42 """Determine if `int_` falls into one of the ranges in `ranges`."""43 tuple_ = _encode_range(int_, 0)44 pos = bisect.bisect_left(ranges, tuple_)45 # we could be immediately ahead of a tuple (start, end)46 # with start < int_ <= end47 if pos > 0:48 left, right = _decode_range(ranges[pos - 1])49 if left <= int_ < right:50 return True51 # or we could be immediately behind a tuple (int_, end)52 if pos < len(ranges):53 left, _ = _decode_range(ranges[pos])54 if left == int_:55 return True56 return False57 