-1

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 ?

LOR13
  • 83
  • 10
  • This [SO question](https://stackoverflow.com/questions/29481088/how-can-i-tell-if-a-string-repeats-itself-in-python) is about strings, but it might be helpful nonetheless. – monk Jun 09 '22 at 08:04

2 Answers2

1
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}")
matszwecja
  • 6,357
  • 2
  • 10
  • 17
0

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.
pasbi
  • 2,037
  • 1
  • 20
  • 32