The Python Oracle

Checking a List for a Sequence

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Checking A List For A Sequence
00:28 Accepted Answer Score 8
01:04 Answer 2 Score 3
01:24 Answer 3 Score 2
01:48 Answer 4 Score 1
02:07 Answer 5 Score 1
02:20 Thank you

--

Full question
https://stackoverflow.com/questions/3411...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 8


You can slice a list. Take the first four elements:

>>> L = ['1','1','1','1','2','2','2'] 
>>> L[:4]
['1', '1', '1', '1']

and the last three:

>>> L[-3:]
['2', '2', '2']

A set does not allow duplicates. Therefore:

 >>> set(L[:4])
 {1}

That means if he length of this set is 1, all elements in the sliced list are the same.

Putting this all together:

>>> len(set(L[:4])) == 1 and len(set(L[-3:])) == 1
True

shows you that your condition is met.




ANSWER 2

Score 3


This should work, just pass each of your sublists into the function:

def all_same(items):
    return all(x == items[0] for x in items)

The above was from the following post: Python: determine if all items of a list are the same item




ANSWER 3

Score 1


Based on the extra details on the question, this can solve the problem:

def check_group_equal(inputList):
    ref = inputList[0]
    for e in inputList[1:]:
        if e != ref:
            return False
    return True

list = some_random_list(length=7)

# Check first group
check_group_equal(list[0:3])

# Check second group
check_group_equal(list[4:7])



ANSWER 4

Score 1


If you can transform your list into string, re will do:

re.match(r'^(.)\1{3}(.)\2{2}$', ''.join(['1','1','1','1','2','2','2']))