I have ranges in a list like:
ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
I would like to find the longest ranges that can be constructed from these (when they overlap with each other).
Expected output:
[(1, 70), (75, 92)]
I have a solution, however it is way too complicated, and I am sure there must be an easier solution to this problem
My solution:
def overlap(x, y):
return range(max(x[0], y[0]), min(x[-1], y[-1]) + 1)
ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
beg, end = min([x[0] for x in ranges]), 0
for i in ranges:
if i[0] == beg:
end = i[1]
while beg:
for _ in ranges:
for i in ranges:
if i[1] > end and overlap(i, [beg, end]):
end = i[1]
print(beg, end)
try:
beg = min([x[0] for x in ranges if x[0] > end])
for i in ranges:
if i[0] == beg:
end = i[1]
except ValueError:
beg = None
Output:
1 70
75 92