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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With