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,117 times
11
siamii
- 21,999
- 26
- 89
- 139
-
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
- 41,719
- 9
- 84
- 75
John La Rooy
- 281,034
- 50
- 354
- 495
-
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