The Python Oracle

Checking a List for a Sequence

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Checking A List For A Sequence
00:27 Answer 1 Score 1
00:42 Answer 2 Score 3
00:59 Accepted Answer Score 8
01:31 Answer 4 Score 1
01:38 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']))