Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a list contains a certain sequence of numbers

Tags:

python

I have a list of 5 ints from 1 to 6 (simulating 5 dice rolling), randomly generated for example:

L = [1,2,3,4,5]

and I want to check that if this list when sorted, contains either

[1,2,3,4] or [2,3,4,5] or [3,4,5,6].

How would I go about checking if list L contains any of the 3 combinations? I don't want to have to go through and check if

L[i] == l1 [i],  L[i]== l2 [i],  L[i]== l3 [i]

for int in the list. I feel like its just a simple question of asking if the list contains either of the other lists or something. I'm just having trouble connecting the dots and its not clicking for me. Any help would be appreciated.

like image 630
Bobby B Avatar asked Mar 02 '15 02:03

Bobby B


Video Answer


1 Answers

The in operator is handy for seeing if a sequence contains a single item, but it doesn't work to check for a list of items. However, it does work on strings, so just convert everything to a string.

s = ''.join(str(i) for i in sorted(L))
if '1234' in s or '2345' in s or '3456' in s:
    # ...

If you had many more conditions to check for you could simplify a little:

if any(sublist in s for sublist in ('1234', '2345', '3456')):
like image 102
Mark Ransom Avatar answered Oct 03 '22 01:10

Mark Ransom