Home > Mobile >  joining list of lines if they have mutual segments?
joining list of lines if they have mutual segments?

Time:05-16

i have list of lines , each line is a list like this

[firstpoint, secondpoint]

for example i have 4 lines like this:

listoflines = [[0,2],[1,3],[2,5],[6,7]]

so as you see some lines have mutual segments what i want is to join them if they have mutual segments therefore the result would be like:

newlistoflines = [[0,5],[6,7]]

what i have tried is to use a function to compare them with each other and loop over my list of lines but i have problem with the its result:

def JOINLINES(line1, line2):
    x1 = line1[0]
    x2 = line1[1]
    x3 = line2[0]
    x4 = line2[1]

    if x2 < x3:
        result = (x1, x2), (x3, x4)
    else:
        result = (min(x1, x2, x3, x4), max(x1, x2, x3, x4))

    return result

newbeamlist = []
for i in range(1, len(beams)):
    newbeamlist.append(JOINLINES(beams[i - 1], beams[i]))

output = [(0, 3), (1, 5), ((2, 5), (6, 7))]

CodePudding user response:

Your solution is appending the result of the JOINLINES function.

It is not considering that the next item could also be a mutual segment.

Try this instead. I have assumed a few things.

# assuming that the items in the list are ordered according to the first item in each sublist. 
# This will enable us to find mutual segments (overlaps) easily
# if the list is not sorted, then we can sort it using the first item in each sublist item

li = [[0,2],[1,3],[2,5],[6,7], [10,11],[7,9]]

# sorting using the first item in each sublist item
li.sort(key=lambda x: x[0])
# out: [[0,5],[6,7]]
newli= []
left_prev = li[0][0]
right_prev = li[0][1]
for i in range(1,len(li)):
    left_current = li[i][0]
    right_current = li[i][1]
    if left_current <= right_prev:
        # mutual segment (overlap) found
        right_prev = right_current
        continue
    else:
        # no mutual segment(overlap), append the previous to the new list
        newli.append([left_prev, right_prev])
        left_prev = left_current
        right_prev = right_current

# appending the last item
newli.append([left_prev, right_prev])
print(newli) # [[0, 5], [6, 9], [10, 11]]
  • Related