boltons
boltons copied to clipboard
Feature request: intersection and union of lists of ranges
Let a range be a pair of sortable objects, e.g. a tuple of numbers, strings, date objects or anything implementing the __lt__
family operators (or maybe a sorting key function should be accepted in the mood of the sorted
builtin!)
Given an iterable of ranges, I find myself rewriting functions to compute the intersection (usually of 2 ranges) and the union of those.
For example
>>> ranges = [(1,5), (2,6), (1,4)]
>>> intersection(ranges)
(2, 4)
>>> union(ranges)
[(1,6)]
>>> ranges = [(1,5), (6,8), (7,9)]
>>> intersection(ranges)
None
>>> union(ranges)
[(1,5),(6,9)]
Input data might be not necessarily ordered.
E.g see https://stackoverflow.com/questions/52073609/get-unions-and-intersections-of-list-of-datetime-ranges-python
I think the boltons library should have a place for functions of this kind!
The very general structure for this I think is the Interval Tree right? https://en.wikipedia.org/wiki/Interval_tree