简体   繁体   中英

Check if python list elemnts respect a pattern

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 ?

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}")

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

I assume you want to check if L is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM