Frazer224
Frazer224

Reputation: 167

Checking a List for a Sequence

I am wanting to check if a list has a specific sequence of elements. I have sorted the list which contains 7 elements, I now want to check of the first 4 are the same as each other and the last 3 are the same as each other.

For what I want to achieve to be True the list would be like this:

list = ['1','1','1','1','2','2','2'] 

I hope this makes what I want to achieve clearer.

Upvotes: 11

Views: 311

Answers (5)

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

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']))

Upvotes: 1

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

If you want to check if list contains 3 items of one element, and 4 items of another, you can omit sorting by using collections.Counter:

content = Counter(['1', '2', '2', '1', '1', '2', '1']).most_common()
print(content) # => [('1', 4), ('2', 3)]

if len(content) == 2 and content[0][1] == 4 and content[1][1] == 3 or
   len(content) == 1 and content[0][1] == 7:
    pass # Your list have desired structure

Upvotes: 2

Mike Müller
Mike Müller

Reputation: 85432

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.

Upvotes: 8

SebasSBM
SebasSBM

Reputation: 908

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])

Upvotes: 1

Simon
Simon

Reputation: 10150

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

Upvotes: 3

Related Questions