Reputation: 91
Consider the following array of ranges:
a = [
[2665.189, 2805.362],
[1304.812, 1429.328],
[2859.97, 2913.514],
[2931.631, 3597.11],
[158.045, 172.058],
[918.479, 929.199],
[263.246, 264.146],
[856.724, 860.121]
]
I want to combine ranges where the difference b/w minimum and maximum of another range with respect to the considered range is less than or equal to 300
i,e
[[2665.189, 2805.362],[2859.97, 2913.514],[2931.631, 3597.11]]
Where the difference between 2859.97 - 2805.365 = 54.608
and 2931.631-2913.514 = 18.117
, so now it become a single range [2665.189, 3597.11]
So continuing like this the final result should be:
a = [
[158.045, 264.146],
[856.724, 929.199],
[1304.812, 1429.328],
[2665.189,3597.11]
]
If any one could suggest a code in python to do this. It will be helpful?
Upvotes: 1
Views: 71
Reputation: 12092
Here you go:
a = [[2665.189, 2805.362], [1304.812, 1429.328], [2859.97, 2913.514], [2931.631, 3597.11], [158.045, 172.058], [918.479, 929.199], [263.246, 264.146], [856.724, 860.121]]
sorted_a = sorted(a, key=lambda x: x[0])
output_a = [sorted_a[0]]
for idx, ele in enumerate(sorted_a[1:], 1):
if ele[0] - sorted_a[idx - 1][1] <= 300:
output_a[-1][1] = ele[1]
else:
output_a.append(ele)
output_a
now has:
[[158.045, 264.146],
[856.724, 929.199],
[1304.812, 1429.328],
[2665.189, 3597.11]]
Upvotes: 2
Reputation: 8614
Here is one solution, not the most elegant one, but working:
RANGE_LIMIT = 300
a = [[2665.189, 2805.362], [1304.812, 1429.328], [2859.97, 2913.514], [2931.631, 3597.11], [158.045, 172.058], [918.479, 929.199], [263.246, 264.146], [856.724, 860.121]]
a = sorted(a)
done = False
while not done:
done = True
for r in range(len(a)-1):
if a[r] == []: continue
if((a[r+1][0] - a[r][1]) < RANGE_LIMIT):
a[r] = [a[r][0], a[r+1][1]]
a[r+1] = []
done = False
a = [x for x in a if x]
print a
Upvotes: 1