What is the most efficient way to find the index of consecutively repeating numbers? The index should be the index of the first number in the consecutively repeating series.
My first thought is the itertools library, but how can i find the index of the number? I tried enumerate and find one solution for this question:
def foo(ls):
result = [None, 0, -1] # record number, number of occurrence, and index
track = [None, 0, -1] # keep track for the current number
for index, value in enumerate(ls):
if value == track[0]:
track[1] += 1
else:
track[0] = value
track[2] = index
if track[1] > result[1]:
result[0] = track[0]
result[1] = track[1]
result[2] = track[2]
return result[2]
For example, if the input is the list [1,2,3,3,3,9,9,9], now the 3 and 9 both consecutively repeated three times, the output should be the index of the bigger one (9), that is, 5. And if the input is the list [1,9,9,3,2,9,9,9] the output should be the index 5.