Home > Back-end >  Python: Merging array of tuples based on difference of [i][1] and [i 1][0]
Python: Merging array of tuples based on difference of [i][1] and [i 1][0]

Time:04-07

I have the following array of tuples:

a = [(0, 657), (1088, 1425), (1427, 1755), (2205, 2856)]

I am trying to merge a tuple at i with the tuple at i 1 based on the following:

currentTuple = a[i]
nextTuple = a[i 1]

diff = nextTuple[0] - currentTuple[1]

if diff < 10:
   #Merge tuple
else:
   #Append

So far I was able to create the following code:

def mergeCloseIndices(indices):
    skip = False
    updatedIndices = []
    for i in range(len(indices)):
        # If the current tuple is merged with the previous, skip it
        if skip:
            skip = False
            if i 1 == len(indices):
                updatedIndices.append(current)
                break
            continue

        current = indices[i]    

        if i 1 == len(indices):
            updatedIndices.append(current)
            break

        next = indices[i 1]

        # Check if current second index is close to next first index
        diff = next[0] - current[1]

        if diff < 10:
            updatedIndices.append((current[0], next[1]))
            skip = True
        else:
            if ~skip:
                updatedIndices.append(current)

    return updatedIndices

Here are my questions:

  1. For the above array, this function works. However, it didn't work for the following array:
b = [(137, 459), (885, 1245), (1247, 1573)]
  1. What if there are 3 consecutive tuples that need to be merged? I wasn't able to figure out a way to handle this.

Cheers!

CodePudding user response:

IIUC:

a = [(0, 657), (1088, 1425), (1427, 1755), (2205, 2856)]

stack = []

while a:
    current = a.pop(0)

    if not stack:
        stack.append(current)
        continue

    last = stack.pop()

    if current[0] - last[1] < 10:
        stack.append((last[0], current[1]))
    else:
        stack.append(last)
        stack.append(current)

print(stack)

Prints:

[(0, 657), (1088, 1755), (2205, 2856)]

For a = [(137, 459), (885, 1245), (1247, 1573)]:

[(137, 459), (885, 1573)]

For a = [(0, 1), (2, 3), (4, 5), (40, 50)]:

[(0, 5), (40, 50)]
  • Related