Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check subsequence exists in a list? [duplicate]

In python, it's possible to use the is keyword to check for contains, e.g.

>>> 3 in [1,2,3,4,5]
True

But this doesn't yield the same output if it's checking whether a list of a single integer is inside the reference list [1,2,3,4,5]:

>>> [3] in [1,2,3,4,5]
False

Also, checking a subsequence in the reference list cannot be achieved with:

>>> [3,4,5] in [1,2,3,4,5]
False

Is there a way to have a function that checks for subsequence such that the following returns true? e.g. a function call x_in_y():

>>> x_in_y([3,4,5], [1,2,3,4,5])
True
>>> x_in_y([3], [1,2,3,4,5])
True
>>> x_in_y(3, [1,2,3,4,5])
True
>>> x_in_y([2,3], [1,2,3,4,5])
True
>>> x_in_y([2,4], [1,2,3,4,5])
False
>>> x_in_y([1,5], [1,2,3,4,5])
False

Maybe something from itertools or operator?

(Note, the input lists can be non-unique)

like image 410
alvas Avatar asked Oct 28 '15 13:10

alvas


1 Answers

x_in_y() can be implemented by slicing the original list and comparing the slices to the input list:

def x_in_y(query, base):
    try:
        l = len(query)
    except TypeError:
        l = 1
        query = type(base)((query,))

    for i in range(len(base)):
        if base[i:i+l] == query:
            return True
    return False

Change range to xrange if you are using Python2.

like image 139
301_Moved_Permanently Avatar answered Oct 16 '22 10:10

301_Moved_Permanently