3

I have some values coming from sensor. My task is to divide them into lists of three elements. If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

values = [1,3,6,8,9,11,15,17,28,29]

I should get:

[1,3,6]
[8,9,11]
[15,17]

I've managed to divide values by list of three:

list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)

But I can't figure out how to compare previous and next value like the task says.

Prune
  • 76,765
  • 14
  • 60
  • 81
AlTs
  • 301
  • 3
  • 9

4 Answers4

1

Before you break the list into triples, you need to find that break point. Iterate through the loop, looking for that difference. For ease of reading, I'm going to call your list vals instead of list_of_values.

for gap in range(1, len(vals)):
    if vals[gap] - vals[gap-1] >= 10:
        break

At this point, gap is the position of the frist element you exclude.

vals = vals[:gap]

Now you're ready to split your list.

Prune
  • 76,765
  • 14
  • 60
  • 81
1

Here is an alternative approach. You can find the absolute difference between consecutive elements using a list comprehension,

diff = [abs(values[i+1]-values[i]) for i in range(len(values)-1)]

The you can find occurrence of the first difference greater than 10 using a generator, which is based on this post,

ind = (i for i,v in enumerate(diff) if v >= 10).next()
lst = values[:ind+1]; 

lst is now your shortened list - i.e. list until and not inclusive the first value different by 10.

Finally, using an approach from this post the shortened list lst can be split into chunks smaller or equal to 3,

n = 3
print [lst[i:i + n] for i in range(0, len(lst), n)]
atru
  • 4,699
  • 2
  • 18
  • 19
1

You can use zip and slicing to pair consecutive elements of a list:

import itertools
diff_less_than_10 = ((a - b < 10)
                     for a, b in zip(list_of_values[1:], list_of_values))
end = 1 + sum(itertools.takewhile(bool, diff_less_than_10))
groups = divide(list_of_values[:end], size)
Harvey
  • 5,703
  • 1
  • 32
  • 41
1

First, calculate where to the index of where to stop the chunking:

stp = [i for i in range(len(values)-1) if values[i]+10 < values[i+1]] [0] 

then chunk to this index:

[values[:stp+1][i:i+3] for i in range(0, stp, 3)]

which outputs:

[[1, 3, 6], [8, 9, 11], [15, 17]]
Prune
  • 76,765
  • 14
  • 60
  • 81
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54