Search code examples
pythonlistiterationlibraries

Python check if indefinite number of consecutive elements in a list satisfy a condition


Basically I am playing around with nested lists, and would like for a given input n, to find if n consecutive elements in the list satisfy a predetermined condition.

For example:

n = 3
lst = [[1,2,3],[6,7,8],[4,5,6],[1,3,4,5]]

And I would like to know if there are n consecutive sublists within lst that have length greater than or equal to 3 (Or some other condition). What is the most efficient way to find firstly:

  1. Is the condition satisfied
  2. The range of indices for when condition is satisfied n times

An example output for my illustrative example would be:

True
index_range = (0,2) #Only need the first instance when n consec achieved

Any help would be greatly appreciated, preferably code which doesn't rely too heavily on inbuilt Python libraries such as itertools or numpy as I am new to Python and would like to better understand how such a process works. Thanks in advance!


Solution

  • different conditionals, one loop, constant memory usage, early exiting

    def func(lst, n, condition):
        n_consec = 0
        if len(lst) < n:
            return (False, None)
        for i,sub in enumerate(lst):
            if condition(sub):
                n_consec += 1
                if n_consec == n:
                    return (True, (i-n+1, i))
            else:
                n_consec = 0
                if len(lst) - (i + 1) < n:
                    return (False, None)
        return (False, None)
    
    print(func(lst,n, lambda sub: len(sub) >= n))