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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With