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.
for i in range(16): light = 0 dark = 0 for j in range(12): index = i + j if index > 15: index -= 15 if list[index] == 1: light += 1 elif list[index] == -1: dark += 1 else: break if dark > 0 and light > 0: break if dark == 12 or light == 12: return True
Advertisement
Answer
I would harness itertools.groupby
following way
import itertools data = [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1] runs = [len(list(g)) for _,g in itertools.groupby(data)] if data[0] == data[-1]: runs[0] += runs.pop() print(max(runs) >= 12) # True
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
.