I have a numpy array like this [1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]
I'd like to find the length of the longest consecutive series of either 1s or -1s. In the example, it should be 3
Asked
Active
Viewed 6,878 times
11

siamii
- 23,374
- 28
- 93
- 143
-
Do you want a `numpy` solution or a pure-python solution is okay? It's trivial using `itertools.groupby`... – Bakuriu May 24 '13 at 10:50
-
So the output in this case should be 2 (-1-1) right ?...ord is there just a "," missing and you actually want 3 (1,1,1) ? – pypat May 24 '13 at 10:50
-
@Bakuriu all pure-python solutions are numpy solutions. The only twist is that sometimes numpy-specific solutions are much nicer or much faster. – Adrian Ratnapala May 24 '13 at 10:51
-
@AdrianRatnapala That solution only works for bits (although it is similar) it is not the same – jamylak May 24 '13 at 11:31
2 Answers
19
In pure Python
>>> from itertools import groupby
>>> L = [1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]
>>> max(sum(1 for i in g) for k,g in groupby(L))
3

John Szakmeister
- 44,691
- 9
- 89
- 79

John La Rooy
- 295,403
- 53
- 369
- 502
-
2
-
-
6@jszakmeister, any time the problem includes the word "consecutive", `groupby()` should be the first thing you thing about – John La Rooy May 24 '13 at 11:34
-
6
Similar to the answer by @AlexMartelli
>>> import numpy as np
>>> nums = np.array([1,1,1,-1-1,1,-1,1,1,-1,-1,-1,1,-1])
>>> run_ends = np.where(np.diff(nums))[0] + 1
>>> np.diff(np.hstack((0, run_ends, nums.size))).max()
3