pythonnumpymore-itertools

How can i return the longest continuous occurrence of "True" in Boolean, and replace other True with False?


I am trying to return a boolean which only gives the longest "True" occurrence in the original boolean and replace shorter "True" chunks into "False". Example a=[True, True, False, True , True, True, False], i want to return [False, False, False, True, True, True, False].

i tried more_itertools and it seems to have some interesting functions but not sure how to exactly implement for my purpose.

a=[True, True, False, True , True, True, False]

pred = lambda x: x in {True}

p=list(mit.run_length.encode(a))

>>>
Results in: (True,2),(False,1),(True,3),(False,1)

So what i want to eventually automatically get is (False,3),(True,3),(False,1). any suggestions? Thank you for your help


Solution

  • Below solution should work after using more_itertools.run_length.

    Essentially, the logic is to find the length of longest subsequence of True, and the location of that index in result list
    then count the total elements before and after that longest subsequence, then construct the resultant list of tuples accordingly.

    import more_itertools as mit
    
    a=[True, True, False, True , True, True, False]
    
    result = list(mit.run_length.encode(a))
    
    #Find the length of longest subsequence of True, and the location if that index in result
    max_true_count = -1
    max_true_idx  = -1
    for idx, (val, count) in enumerate(result):
        if val and max_true_count < count:
            max_true_count = count
            max_true_idx = idx
    
    #Find total elements before and after the longest subsequence tuple
    elems_before_idx = sum((idx[1] for idx in result[:max_true_idx]))
    elems_after_idx = sum((idx[1] for idx in result[max_true_idx+1:]))
    
    #Create the output list using the information
    output = [(False, elems_before_idx), (True, max_true_count), (False, elems_after_idx)]
    print(output)
    

    The output will be

    [(False, 3), (True, 3), (False, 1)]