Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Created December 4, 2019 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonagestam/93066a7085b47a2e6419ae5b005b9314 to your computer and use it in GitHub Desktop.
Save antonagestam/93066a7085b47a2e6419ae5b005b9314 to your computer and use it in GitHub Desktop.
def inclusive_range(start: int, stop: int) -> range:
"""
>>> list(inclusive_range(0, -1))
[0, -1]
"""
if stop > start:
return range(start, stop + 1)
return range(start, stop - 1, -1)
def intersection(a: range, b: range) -> range:
"""
Return the intersection of two one-step ranges as a new range. The new
range will have the step sign of `a` if `a` and `b` differ.
Usage:
>>> tuple(intersection(inclusive_range(0, 2), inclusive_range(1, 3)))
(1, 2)
>>> tuple(intersection(inclusive_range(2, 0), inclusive_range(3, 1)))
(2, 1)
>>> tuple(intersection(inclusive_range(0, 2), inclusive_range(3, 1)))
(1, 2)
>>> tuple(intersection(inclusive_range(3, 1), inclusive_range(0, 2)))
(2, 1)
"""
assert not {a.step, b.step} - {1, -1}
if 1 == b.step == a.step:
return range(max(a.start, b.start), min(a.stop, b.stop), a.step)
elif -1 == b.step == a.step:
return range(min(a.start, b.start), max(a.stop, b.stop), a.step)
elif 1 == a.step:
# a is increasing, b is decreasing
return range(max(a.start, b.stop) + 1, min(a.stop, b.start), a.step)
elif -1 == a.step:
# a is decreasing, b is increasing
return range(min(a.start, b.stop) - 1, max(a.stop, b.start), a.step)
raise TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment