Home > database >  Divide list into groups based on adjoining difference values
Divide list into groups based on adjoining difference values

Time:10-17

I have following issue with grouping element in list. After digital image transformation I separated holes centers and collect them in values list, then after calcutaions differences between adjoining element I have got diff_ar. Now I want to get indexes of elements which belongs to one group/cluster. I assume that max difference between element in one section should be less than 3. In addition group can be created only when have at least 7 elements inside. As a result I expect list of tuples which contains index start and index end each od detected group (2 in this example).

Image for better issue statement

values = [73.0, 143.0, 323.0, 324.0, 325.0, 325.0, 325.0, 325.0, 325.5,
          325.5, 326.0, 326.0, 326.0, 326.0, 406.0, 406.5, 432.5, 433.0,
          433.5, 434.5, 435.0, 435.0, 436.0, 436.5, 437.5, 438.0]

diff_ar = [70.0, 180.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0,
           0.0, 0.0, 80.0, 0.5, 26.0, 0.5, 0.5, 1.0, 0.5, 0.0, 1.0, 0.5,
           1.0, 0.5]

expected_output = [(2,12),(16,24)]

CodePudding user response:

First solution: use more_itertools.split_when.

import more_itertools

values = [73.0, 143.0, 323.0, 324.0, 325.0, 325.0, 325.0, 325.0, 325.5,
          325.5, 326.0, 326.0, 326.0, 326.0, 406.0, 406.5, 432.5, 433.0,
          433.5, 434.5, 435.0, 435.0, 436.0, 436.5, 437.5, 438.0]

threshold = 3
min_items = 7
groups = [(g[0][0], g[-1][0]) for g in more_itertools.split_when(enumerate(values), lambda x,y: abs(x[1]-y[1])>=threshold) if len(g) >= min_items]

print(groups)
# [(2, 13), (16, 25)]

Second solution: write the loop yourself.

def split_values(values, threshold, min_items):
    result = []
    prev = values[0]
    last_cut = 0
    for i,x in enumerate(values[1:], start=1):
        if abs(x - prev) >= threshold:
            if i - last_cut >= min_items:
                result.append((last_cut, i-1))
            last_cut = i
        prev = x
    if len(values) - last_cut >= min_items:
        result.append((last_cut, len(values)-1))
    return result

values = [73.0, 143.0, 323.0, 324.0, 325.0, 325.0, 325.0, 325.0, 325.5,
          325.5, 326.0, 326.0, 326.0, 326.0, 406.0, 406.5, 432.5, 433.0,
          433.5, 434.5, 435.0, 435.0, 436.0, 436.5, 437.5, 438.0]

print(split_values(values, 3, 7))
# [(2, 13), (16, 25)]
  • Related