Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a List for a Sequence

Tags:

python

list

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.

like image 425
Frazer224 Avatar asked Dec 06 '15 13:12

Frazer224


People also ask

How do you find a sequence in a list?

As we know an arithmetic sequence is a list of numbers where the difference between one number and the next number is the same. otherwise, ans := ans + quotient of (count * (count + 1)) / 2.

How do you check if a list is in a sequence in Python?

The function takes a list of integers and returns True if the given list contains the sequence, for example, [1, 2 ,3] at any point in the list, and False otherwise. The target sequence will be pre-determined for the function. I tried indexing via: if nums[i] == 1, if nums[i+1] == 2, if nums[i+2] == 3, return False.

How do you check if an input is already in a list?

Use the in operator to check if a user input value is in a list, e.g. if user_input in my_list: . The in operator will return True if the input value is in the list and False otherwise.


3 Answers

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.

like image 76
Mike Müller Avatar answered Oct 05 '22 23:10

Mike Müller


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

like image 37
Simon Avatar answered Oct 06 '22 00:10

Simon


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
like image 36
GingerPlusPlus Avatar answered Oct 05 '22 23:10

GingerPlusPlus