Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the length of the longest consecutive series of numbers [duplicate]

Tags:

python

numpy

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

like image 420
siamii Avatar asked May 24 '13 10:05

siamii


People also ask

How do you find a consecutive sequence?

Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max. First sort the array to arrange them in consecutive fashion. Now, store the distinct elements from the sorted array.

Which algorithm is used to find longest consecutive subsequence?

Naive Approach: A normal approach will be to iterate for every element and find out the longest increasing subsequence. For any particular element, find the length of the subsequence starting from that element. Print the longest length of the subsequence thus formed. The time complexity of this approach will be O(n2).

How do you find the longest array sequence?

A simple solution is to use two nested loops. In the outer loop, we look for positive elements. In the inner loop, we count number of positives starting with the positive element picked by outer loop. Time complexity of this solution is O(n^2).


1 Answers

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
like image 129
John La Rooy Avatar answered Oct 20 '22 05:10

John La Rooy