I\'m trying to write code that finds the longest run in a list of Boolean values and return the index of the first and last value of that run. For example, if L is [False, Fals
You can keep track of the starting index and the length of the longest run so far, as well as the starting index of the current run, and if the current index minus the starting index of the current run is greater than the length of the longest run so far, make the current starting index and the said length the new starting index and the length of the longest run:
def longest_false(L):
start = max_start = None
max_size = -1
for i, v in enumerate(L):
if v:
start = None
else:
if start is None:
start = i
if i - start > max_size:
max_start = start
max_size = i - start
if max_start is None:
return None, None # in case there is no False at all in the given list
return max_start, max_start + max_size