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

前端 未结 3 649
抹茶落季
抹茶落季 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 10:49

    Use itertools.groupby:

    from itertools import groupby
    
    values = [False, False, True, False, False, False, False, True, True, False, False]
    
    start = 0
    runs = []
    for key, run in groupby(values):
        length = sum(1 for _ in run)
        runs.append((start, start + length - 1))
        start += length
    
    result = max(runs, key=lambda x: x[1] - x[0])
    print(result)
    

    Output

    (3, 6)
    

提交回复
热议问题