Skip to content
Advertisement

Check if a Python list has X number of consecutive values equal to Y

I have a collection of lists each containing 16 items, and I want to find lists with 12 consecutive values either > or < than a specified threshold. For now, I have iterated through the lists and put 1 for values greater and -1 for values less than the threshold, and I used to following to eliminate those that don’t have 12 of either.

if list.count(-1) >= 12 or list.count(1) >= 12:

How do I efficiently check for 12 consecutive values? (12 values can loop around) for example this would count

[1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Currently I have 2 nested for loops, but I know this checks the same value multiple times.

JavaScript

Advertisement

Answer

I would harness itertools.groupby following way

JavaScript

Explanation: I use itertools.groupby to get length of runs (in this case [7,4,5]) – itertools.groupby does group only adjacent equal elements, then if first and last values of data are equal I extract last element from runs and add it to first element (as you allow wraparound), then I check if longest run is equal or greater 12.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement