jpayne@69: """ jpayne@69: Given a list of integers, made up of (hopefully) a small number of long runs jpayne@69: of consecutive integers, compute a representation of the form jpayne@69: ((start1, end1), (start2, end2) ...). Then answer the question "was x present jpayne@69: in the original list?" in time O(log(# runs)). jpayne@69: """ jpayne@69: jpayne@69: import bisect jpayne@69: from typing import List, Tuple jpayne@69: jpayne@69: jpayne@69: def intranges_from_list(list_: List[int]) -> Tuple[int, ...]: jpayne@69: """Represent a list of integers as a sequence of ranges: jpayne@69: ((start_0, end_0), (start_1, end_1), ...), such that the original jpayne@69: integers are exactly those x such that start_i <= x < end_i for some i. jpayne@69: jpayne@69: Ranges are encoded as single integers (start << 32 | end), not as tuples. jpayne@69: """ jpayne@69: jpayne@69: sorted_list = sorted(list_) jpayne@69: ranges = [] jpayne@69: last_write = -1 jpayne@69: for i in range(len(sorted_list)): jpayne@69: if i + 1 < len(sorted_list): jpayne@69: if sorted_list[i] == sorted_list[i + 1] - 1: jpayne@69: continue jpayne@69: current_range = sorted_list[last_write + 1 : i + 1] jpayne@69: ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) jpayne@69: last_write = i jpayne@69: jpayne@69: return tuple(ranges) jpayne@69: jpayne@69: jpayne@69: def _encode_range(start: int, end: int) -> int: jpayne@69: return (start << 32) | end jpayne@69: jpayne@69: jpayne@69: def _decode_range(r: int) -> Tuple[int, int]: jpayne@69: return (r >> 32), (r & ((1 << 32) - 1)) jpayne@69: jpayne@69: jpayne@69: def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool: jpayne@69: """Determine if `int_` falls into one of the ranges in `ranges`.""" jpayne@69: tuple_ = _encode_range(int_, 0) jpayne@69: pos = bisect.bisect_left(ranges, tuple_) jpayne@69: # we could be immediately ahead of a tuple (start, end) jpayne@69: # with start < int_ <= end jpayne@69: if pos > 0: jpayne@69: left, right = _decode_range(ranges[pos - 1]) jpayne@69: if left <= int_ < right: jpayne@69: return True jpayne@69: # or we could be immediately behind a tuple (int_, end) jpayne@69: if pos < len(ranges): jpayne@69: left, _ = _decode_range(ranges[pos]) jpayne@69: if left == int_: jpayne@69: return True jpayne@69: return False