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