Home > other >  Check if python list elemnts respect a pattern
Check if python list elemnts respect a pattern

Time:06-09

I have a list that looks like :

L = [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1]

I want to check if the sequence 2-1-2 is always respected or I have an outlier somewhere . Is there a simple way to do this with python ?

CodePudding user response:

from itertools import cycle

L = [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

seq = cycle([2, 1])

for idx, el in enumerate(L):
    if not el == next(seq):
        raise ValueError(f"Sequence not followed at index {idx}")

CodePudding user response:

What does "2-1-2 is always respected" mean, precisely?

I assume you want to check if Lis an alternating sequence of 2 and 1, starting with 2.

That's easy to check:

def check(L):
    if len(L) < 3:
        return False
    even_indices_all_two = set(L[::2]) == {2}
    odd_indices_all_one = set(L[1::2]) == {1}
    return even_indices_all_two and odd_indices_all_one and L[-1] == 2
  • If you don't require L to end with 2, remove the and L[-1] == 2.
  • If you wonder about the many colons, check this post to understand slicing.
  • I use the set to check if a sequence contains only one distinct item.
  • Related