Function to find the index of the beginning and end of the longest run in a list

前端 未结 3 704
抹茶落季
抹茶落季 2021-01-29 10:16

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

3条回答
  •  忘掉有多难
    2021-01-29 11:07

    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
    

提交回复
热议问题